Flutter Session API Login - flutter

I am trying to log in with the help of API and after login wants to see dashboard.
but I am getting a message {status: error, message: Seller Not Logged In}
I tried creating a session of login but it didn't work.
Login Page
postMethod() async {
var api = Uri.parse("https://www.nearxt.com/index.php?route=api/userlogin");
Map mapeddate ={
'email':_email.text,
'password':_password.text,
};
final response= await post(api,body: mapeddate);
if(response.statusCode==200)
{
await FlutterSession().set('token',_email.text);
print("Session Created");
}
var res = json.decode(response.body);
print(res);
}
it gives the output: Session Created
{cust: Login Success, error_warning: , success: }
after this, on homepage, I am trying to access the products after the login
Future fetchSellerProduct() async {
FlutterSession().get('token');
var url = await http.post(Uri.parse(
"https://www.nearxt.com/index.php?route=api/purpletree_multivendor/api/sellerproduct"));
if(url.statusCode==200)
{
print(url.statusCode);
}
setState(() {
map = json.decode(url.body);
print(map);
});
}
Output: {status: error, message: Seller Not Logged In}

Related

Flutter - Keycloak integration with openId ( redirecting issue )

I want to authenticate flutter app with Keycloak service via internal webview (without open web browser)
To achieve this objective I used OpenID
When app runs will appear Keycloak login page in internal webview. But when entering the username and password correctly, it redirects to another web page which is as follows.
I guess this case happen due to flutter app cannot handle custom redirections. Does anyone know how to fix this??
My code:
urlLauncher(String url) async {
if (await canLaunch(url)) {
await launchUrlString(url, mode: LaunchMode.inAppWebView);
} else {
print("TOKEN = error");
throw 'Could not launch $url';
}
}
// create an authenticator
var authenticator = new Authenticator(
client,
redirectUri: Uri.parse(_redirectUrl),
scopes: scopes,
urlLancher: urlLauncher,
);
// starts the authentication
var c = await authenticator.authorize();
print("TOKEN = DONE");
// close the webview when finished
await closeInAppWebView();
var res = await c.getTokenResponse();
print("TOKEN = ${res.accessToken}");
pubspec.yaml:
openid_client: ^0.4.6
url_launcher: ^6.1.6
I tried open id , simple auth , flutter app auth also, unfortunately flutter app auth cannot use with internal webview
Future<TokenResponse> authenticate(Uri uri, String clientId,
List<String> scopes, BuildContext context) async {
try {
var issuer = await Issuer.discover(uri);
var client = Client(issuer, clientId);
urlLauncher(String url) async {
Uri uri = Uri.parse(url);
if (await launchUrl(uri)) {
} else {
throw 'Could not launch $url';
}
}
var authenticator = Authenticator(
client,
scopes: scopes,
urlLancher: urlLauncher,
port: 3000,
);
var c = await authenticator.authorize();
await closeInAppWebView();
var res = await c.getTokenResponse();
UserInfo use = await c.getUserInfo();
authUserId(use.subject.toString());
email(use.email.toString());
token(res.accessToken.toString());
logoutUrl = c.generateLogoutUrl();
return res;
} finally {
context.loaderOverlay.hide();
}
}
You can try this out.
Saved the logout URL into a variable cos it'll be needed to logout.

next-auth pass the data in signin callback

I am making login process with next-auth.
I am using Google as OAuth Provider.
// pages/api/auth/[...nextauth].ts
export default async function auth(req: any, res: any) {
return await NextAuth(req, res, {
//...
callbacks: {
async signIn({ user, account }) {
// console.log(user); // data exists.
const isUser = await apiForIsUser();
if(isUser) return true; // redirect to root page.
return '/sign-up'; // redriect to sign-up page.
}
}
});
}
above code works, but I can not touch data from OAuthProvider in sign-up page.
How can I pass the data from 'OAuthProvidertosign-up` page?

Stripe Connect firebase functions for creating seller account

I'm using Firebase functions for creating seller account but I don't know how to create seller account and what to put in the redirect_url
I followed some tutorials and wrote the below code
Let me know what changes should I do to open seller account registration with url_launcher
Thanks
const stripeAccount = functions.https.onRequest(async (req, res) => {
const { method } = req
if (method === "GET") {
// CREATE CONNECTED ACCOUNT
const { mobile } = req.query
const account = await stripe.accounts.create({
type: "express",
})
const accountLinks = await stripe.accountLinks.create({
account: account.id,
refresh_url:, <-- What to put here
return_url:, <-- What to put here
type: "account_onboarding",
})
if (mobile) {
// In case of request generated from the flutter app, return a json response
res.status(200).json({ success: true, url: accountLinks.url })
} else {
// In case of request generated from the web app, redirect
res.redirect(accountLinks.url)
}
} else if (method === "DELETE") {
// Delete the Connected Account having provided ID
const {
query: { id },
} = req
console.log(id)
const deleted = await stripe.accounts.del(id)
res.status(200).json({ message: "account deleted successfully", deleted })
} else if (method === "POST") {
// Retrieve the Connected Account for the provided ID
// I know it shouldn't be a POST call. Don't judge :D I had a lot on my plate
const account = await stripe.accounts.retrieve(req.query.id)
res.status(200).json({ account })
}
const stripeReAuth = async (req, res) => {
const { account_id: accountId } = req.query
const accountLinks = await stripe.accountLinks.create({
account: accountId,
refresh_url: <-- Here
return_url: , <-- Here
type: "account_onboarding",
})
res.redirect(accountLinks.url)
}
})
This is my flutter code, I'm retrieving the return_url and launching it with url_launcher
class StripeBackendService {
static String apiBase = '{function address}/stripeAccount';
static String createAccountUrl =
'$apiBase/account?mobile=true';
static String checkoutSessionUrl =
'${StripeBackendService.apiBase}/checkout-session?mobile=true';
static Map<String, String> headers = {'Content-Type': 'application/json'};
void createSellerAccount() async {
var url = Uri.parse(StripeBackendService.createAccountUrl);
var response = await http.get(url, headers: StripeBackendService.headers);
Map<String, dynamic> body = jsonDecode(response.body.toString());
await canLaunch(body['url']) ? await launch(body['url']) : throw 'Error'
}
}
The refresh url should point to an address that retries the creation of the stripe connect account, in case your current http function returns an expired link. The return url is the address that the potential stripe connect user gets sent to after the stripe onboarding is complete. In knowing that address you can use the webview controller to jump back to the app when reaching that return-url endpoint.

Google Auth Page always shown, how to Auth only first time

I am making a calendar app with flutter using googleApi library.
but, When you turn off the app, need to auth again in web site.
i want auth only first time.
is it possible?
// mycode
get _SCOPES => [CalendarApi.CalendarScope];
await clientViaUserConsent(_clientID, _SCOPES, prompt)
.then((AuthClient client) async {
CalendarClient.calendar = CalendarApi(client);
calendarId = await CalendarClient.calendar.calendarList
.list()
.then((value) => value.items[0].id);
});
void saveData(AccessCredentials credentials) {
GetStorage().write(credetialKey, {
"accessTokenData": credentials.accessToken.data,
"accessTokenExpiry": credentials.accessToken.expiry.toString(),
"refreshToken": credentials.refreshToken,
"scopes": credentials.scopes,
"idToken": credentials.idToken
});
}
AccessCredentials getCredetial() {
try {
var map = GetStorage().read(credetialKey);
return AccessCredentials(
AccessToken("Bearer", map["accessTokenData"] as String,
DateTime.parse(map["accessTokenExpiry"])),
map["refreshToken"],
map["scopes"].cast<String>(),
idToken: map["idToken"] as String);
} catch (e) {
return null;
}
}
Client cli = Client();
var c = await refreshCredentials(_clientID, getCredetial(), cli)
.catchError((e) {
print(e);
});
authenticatedClient(cli, c);
error :
DetailedApiRequestError(status: 401, message: Request is missing required authentication credential. Expected OAuth 2 access tok
You can save user session using for example sharedPreferences. Each time the user launch the app your must first check if the session is saved so you can skip the auth process, otherwise you initiate the authentication
i solved it.
save AccessCredentials,
and use autoRefreshingClient;
Client cli = Client();
var c = await refreshCredentials(_clientID, getCredetial(), cli)
.catchError((e) {
print(e);
});
cli = autoRefreshingClient(_clientID, c, cli);

Login to Flutter Facebook Login

I'm having a problem with the facebook login with flutter.
I followed a lot of tutorials but it's from 2018, 2019, so it doesn't match the version of flutter_facebook_login: ^3.0.0.
the process works very well when I launch it redirects me to facebook I enter my details I log in as MyFacebookName, the problem is that when I click on Ok it redirects me to the login page and it does not register the user on my Firebase console. Here is the code
// Facebook connection configuration
static final FacebookLogin facebookSignIn = new FacebookLogin();
String _message = 'Login or logout by pressing the buttons below.';
Future<void> _login() async {
final FacebookLoginResult result =
await facebookSignIn.logIn(['email']);
switch (result.status) {
FacebookLoginStatus.loggedIn box:
final FacebookAccessToken accessToken = result.accessToken;
_showMessage(''')
Sign in!
Token: ${accessToken.token}
User id: ${accessToken.userId}
Expires: ${accessToken.expires}
Permissions: ${accessToken.permissions}
Declined permissions: ${accessToken.declinedPermissions}
''');
break;
checkbox FacebookLoginStatus.cancelledByUser:
_showMessage("login cancelled by user.");
break;
checkbox FacebookLoginStatus.error:
"Something went wrong during the login process."
"Here's the error Facebook gave us: ${result.errorMessage}");
break;
}
}
Future<Null> _logOut() async {
await facebookSignIn.logOut();
_showMessage('Logout.');
}
void _showMessage(String message) {
setState(() {
_message = message;
});
}
//connection button
_buildSocialBtn(
() {
_login();
},