ERPNext: How can I generate user session without Password? - authentication

As an ERPNext fresher, I am creating a REST API for the mobile app, where the use case is, the Mobile user will send a request to do login using Face authentication, as a result of Face authentication at the mobile end, it will return User ID(same as ERPNext UserID).
As a Param, I will get UserID and other params of API request, here in response, I have to send a new session generated for that User.
Applied solution:
Tried Login by fetching password of user based on UserID, which basically gives encryption error for encrypted password.
Tried bypass login and generate new session, failed due to password not being added
Decrypt the password to use as param for new session
My current problem is, I don't have Password in normal format, and need to generate a valid user session, for the next operation post face recognization(face validation is already done through SDK).

You can use token based authentication for REST Api, based on your question when you receive emailid (same as erpnext user id), you can identify the user and generate api_key and api_secret, you can return these keys in response to your request, also you can store these secrets keys and use for future requests to authenticate it
You can refer docs here https://frappeframework.com/docs/user/en/api/rest#1-token-based-authentication
Below is sample code, please note code is not tested, posted just for reference
#frappe.whitelist(allow_guest=True)
def validate_user(email):
user_email = frappe.db.get_all('User', filters={'name': email}, fields=['name'])
user = frappe.get_doc('User', user_email[0]['name'])
api_generate = generate_keys(user.name)
user_resp = frappe.get_doc('User', user.name)
frappe.response["message"] = {
"status": 1,
"message": "Authentication success",
"api_key": user_resp.api_key,
"api_secret": api_generate,
"username": user.username,
"email": user_resp.email,
"role": user_resp.roles[0].role
}
def generate_keys(user):
user_details = frappe.get_doc('User', user)
api_secret = frappe.generate_hash(length=15)
if not user_details.api_key:
api_key = frappe.generate_hash(length=15)
user_details.api_key = api_key
frappe.db.set_value('User', user, 'api_secret', api_secret)
return api_secret

Related

"error": "unauthorized_client", "error_description": "AADSTS700016 (Microsoft Graph API)

I want to access my todo list using Microsoft graph API and so registered an app and after doing the required steps got the access token, but after trying to get the new access token using the refresh token it returns this message: "error": "unauthorized_client", "error_description": "AADSTS700016: Application with identifier 'id' was not found in the directory 'Microsoft Accounts'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant
class Refresh:
def __init__(self):
self.refresh_token = refresh_token
self.scope = scope
self.client_secret = client_secret
def refresh(self):
query = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
response = requests.post(query,
data={"client_id" : client_id,
"scope": 'Tasks.Read%20Tasks.Read.Shared%20Tasks.ReadWrite%20Tasks.ReadWrite.Shared%20offline_access',
"refresh_token": refresh_token,
"redirect_uri": 'https://github.com/Rohith-JN',
"grant_type": "refresh_token",
"client_secret": client_secret
},
headers={"Content-Type": "application/x-www-form-urlencoded"})
response_json = response.json()
print(response)
print(response_json)
a = Refresh()
a.refresh()
I am also not sure if I am entering the scopes in the right way. Any help would be really appreciated
I finally figured it out by changing the URL that refreshes the token from
https://login.microsoftonline.com/common/oauth2/v2.0/token to this https://login.microsoftonline.com/{tenant_id}/oauth2/token

bigCommerce customer api - Customer JWT for sso

In my app (node-bigcommerce-sdk) my customers will need to login as if they were on the bc store. I am able to verify that the provided email and password are correct. I cant find a method to exchange the user_id and my app credentials for a token that can be used in sso (described here)
I used the python sdk before and the part I want to do now in nodejs is the following
bc_client = b.api.BigcommerceApi(client_id, store_hash, access_token)
login_token = sdk.customer_login_token.create(bc_client, customer.id)
so far (not working)
let token = jwt.encode({
"iss": account.clientId,
"iat": 123456789,
"jti": "uid-"+uid,
"operation": "customer_login",
"store_hash": account.storeHash,
"customer_id": uid,
}, account.secret, 'HS512');
let sso_url = `${account.entry_url}/login/token/${token}`
example token received
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJja244ZzN5Z3V4MmY0cG14ZWw0M2dqbmJjOTViZ2FrIiwiaWF0IjoxMjM0NTY3ODksImp0aSI6InVpZC0xIiwib3BlcmF0aW9uIjoiY3VzdG9tZXJfbG9naW4iLCJzdG9yZV9oYXNoIjoiMmJpaHByMnd2eiIsImN1c3RvbWVyX2lkIjoiMSJ9.n4lygAJtfqhcrHnGEWle1far-Ee69xrgym-HWFWWwNWXB1-hBziKC03SK_y8PYjLBL_n43Q6K07YH9ysSV5a4g
${account.entry_url}/login/token/${token} results in an error message on the frontend Invalid login. Please attempt to log in again.

auth0 - email verification - user account does not exist or verification code is invalid

Here is my problem : In auth0 dashboard, I select a user within my users list and click on send a verification email... The user receive the mail, click on the link and get an error "User account doesn't exist or verification code is invalid" But the user exists and I do not use passwordless or sms authentication , my users have to enter their password and are also stored in mongodb. Any ideas to solve this?
-- edited precision added --
#Arcseldon
I'am actually using a customDB and here is my getUser script, but I don't know what to change, could you help me?
Thank you!
function getByEmail (email, callback) {
mongo('mongodb://user:pass#dsXXXX.mlab.com:XXXX/base', function (db) {
var users = db.collection('user');
users.findOne({ email: email }, function (err, user) {
if (err) return callback(new Error("my error message"));
if (!user) return callback(null);
var profile = {
user_id: user._id,
nickname: user.username,
email: user.email,
};
callback(null, profile);
});
});
}
Ok, just re-read your question - where you state "my users have to enter their password and are also stored in mongodb." - are you referring to your own Mongo DB? Are you using an Auth0 Custom DB Connection? Confusingly, Auth0 also uses MongoDB for its own DB storage, hence the clarification. If you are using a Custom DB connection to your own DB, then this may be a misconfiguration of one of your Custom DB Scripts. If using Custom DB Script, please double-check the implementation of your GetUser.js script.
In the event, you are using an Auth0 DB (not a custom DB) then definitely check with Auth0 support team (as per comment and your reply above).

Meteor Accounts obtaining the SAML Response (Token / User after log in)

i have a workin SAML logon with Meteor.accounts and MS Azure. I am using this https://github.com/steffow/meteor-accounts-saml library for SAML which is derived from https://github.com/bergie/passport-saml
The procedure goes like this:
Click saml login -> popup appears
Enter user/pw data in popup -> popup closes without error
Logged in success
So now i want to get the SAML Token for further processing (or at least the information about the logged in user which meteor has taken from the IDP).
Since i dont have a clue where the SAML Token is stored by Meteor or can be fetched in the code, can someone help me getting the SAML Response?
Probably solved by now but here it goes..
According to the code the saml response is retrieved in "saml_server.js" at row 70 and the token should be in there also (loginRequest.credentialToken)
loginResult should be fairly easy to save into the Meteor.users collection
var loginResult = Accounts.saml.retrieveCredential(loginRequest.credentialToken);
var email = loginResult.profile.email;
var user = Meteor.users.findOne({username: email});
if (!user) {
Accounts.createUser({
"username": email,
"profile": StufffromloginResult
});
} else {
Meteor.users.update(
{
"username": email
},
{ "$set": {
"profile": StufffromloginResult,
}
});
}
And retrieved with:
Meteor.user().profile

How to find access_token expired or not in Onedrive?

In Onedrive I am able to use their Live SDK API and get the Access_token and the filepicker for my users is also working properly.
But, every time a user tries to attach a file I am calling the API to get the Access_token.
Is this a problem, when more number of users try to call this API every time they try to attach the files( did Microsoft has a limit for number of API call).
Also, If i try to use Refresh_token for Access_token using WL.offline_access scope how would my app know the Access_token is expired?
You'll need to add logic to your code to see if the user is already has a session occurring. You can do this this by adding WL.Event.subscribe and checking for "auth.statusChange". If the users status has changed at any point, it will call the function to check the users current status (i.e. connect, notConnected, and unknown) by calling WL.getLoginStatus. WL.getLoginStatus will also return the users session object (access_token, expires_in, etc) if you want to use any values there.
Your code will look something like this.
< script type = "text/javascript" >
WL.Event.subscribe("auth.statusChange", chkStatus);
function chkStatus() {
WL.getLoginStatus(
function(response) {
if (response.status == "connected") {
document.getElementById("info").innerText = "You're signed in";
} else {
WL.login({
"scope": "wl.skydrive_update"
});
}
More info on WL.getLoginStatus can be found at https://msdn.microsoft.com/EN-US/library/hh550842.aspx. I hope that helps.