Add Okta user to Okta group Python sdk - okta

Is there a method to add a user to an Okta group? I see update_group, but nothing specific on how to add a user to an Okta group.

The latest updates to the SDK have add_user_to_group(group, user) and add_user_to_group_by_id(gid, uid) methods on UserGroupsClient.
from okta import UserGroupsClient
from okta.models.usergroup import UserGroup
from okta import UsersClient
from okta.models.user import User
groups_client = UserGroupsClient('your_url', 'your_key')
users_client = UsersClient('your_url', 'your_key')
# Create group
group = UserGroup(name='sample_name',
description='sample description')
group = groups_client.create_group(group)
# Create user
user = User(login='sample#asdf.com',
email='fake#asdf.com',
firstName='Joe',
lastName='Schmoe')
user = users_client.create_user(user, activate=False)
groups_client.add_user_to_group(group, user)
# or
groups_client.add_user_to_group_by_id(group.id, user.id)
To get the latest:
pip install git+git://github.com/okta/oktasdk-python#master

Related

Getting user details from access token in Django rest framework -simple JWT

I am using React and Django rest framework for a project. I use Django rest framework simple JWT for authentication. Now, I want to display the username in the navbar after the user logs in. So, is there a way in simple JWT for returning user details from the access token generated after authentication, just like Djoser returns user credentials when supplied the access token?
Sorry if this question is silly but I was not able to find a solution to this anywhere.
if you want to obtain the information of the owner of the token you can consult it in REQUEST.
class ViewProtect(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def post(self, request, format=None):
token_user_email = request.user.email
token_user_username = request.user.username
pass
About the backend, basically I use this library
from restframework_simplejwt.tokens import AccessToken
The function AccessToken() take as input the string access_token_str and return the object access_token_obj.
To get the user_id, you can use the instruction
user_id=access_token_obj['user_id'].
In the following example I have created the function
get_user_from_access_token_in_django_rest_framework_simplejwt().
This function is just a wrapper around AccessToken()
Full code:
#Path current file
#/blabla/django/project004/core/view.py
from restframework_simplejwt.tokens import AccessToken
from django.contrib.auth.models import User
#Example data.
#access_token_str = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU'
def get_user_from_access_token_in_django_rest_framework_simplejwt(access_token_str):
access_token_obj = AccessToken(access_token_str)
user_id=access_token_obj['user_id']
user=User.objects.get(id=user_id)
print('user_id: ', user_id )
print('user: ', user)
print('user.id: ', user.id )
content = {'user_id': user_id, 'user':user, 'user.id':user.id}
return Response(content)
Credits:
#davesque;
https://github.com/jazzband/djangorestframework-simplejwt/issues/140
Update.
The string access_token_str I write in the file is just an example. You should pass it as argument.
Here's how I've done it.
On Django, I followed the steps described on this page in order to add the user's name inside the JWT token : https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
#classmethod
def get_token(cls, user):
token = super().get_token(user)
# Add name to token
token['name'] = user.get_full_name()
# You can add other information into the token here
return token
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer
Then, I updated my urls.py to use the custom view:
path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
Finally, in my Vue.js application, I installed the jwt-decode package and used it like this:
const token = localStorage.getItem('access_token');
const decoded = jwt_decode(token);
console.log(decoded)
// decoded.name contains the user's full name
Note that I store the access token in the local storage beforehand.

allow admins to read users mails using GSuite app

right now i'm trying to build an app for G Suit marketplace which allow the admins to read users emails using Gmail APIs. I found that we can do that by using a service account but i only can access the users emails in my domain. right now i don't know how i can make admins from outside my organization use my app to read users emails
from googleapiclient import discovery
from google.oauth2 import service_account
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
SERVICE_ACCOUNT_FILE = 'service_file2.json'
emails=['user2#example.com','user1#example.com']
for email in emails:
# The user we want to "impersonate"
USER_EMAIL = email
credentials = service_account.Credentials.\
from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject(USER_EMAIL)
service = discovery.build('gmail', 'v1', credentials=delegated_credentials)
email_list = service.users().messages().list(userId=USER_EMAIL).execute()
b = 3
for m in email_list['messages']:
message = service.users().messages().get(userId=USER_EMAIL, id=m['id'], format='metadata').execute()
print(message['payload']['headers'][1]['value'])

Ember-Django Rest: Delete an authorised user account from an admin account

If the user accounts are authenticated using jwt authentication,
(backend - Django rest), how can I delete a user account from another account which is an admin account(superuser) ?
You can use django admin panel or create view
class ExampleView(APIView):
permission_classes = (IsAdminUser,)
def delete(self, request, pk=None):
user = get_object_or_404(User.objects, pk=pk)
user.delete()
return Response(status=status.HTTP_200_OK)
Then you have to link it with url containing pk parameter

Redirecting to login page after Session Expired in Spring

1 I am facing a problem. I have 3 role in my project user,admin,expert.
2 3 different login page for different user.
3 What I have want is when ever the session is expired,and after that if User did any event the page should direct to according to there role.
e.g User should get redirect to User login and Admin to admin a login.
I have read many document about it.Some has give idea of adding filter and check the session in filter.
But the issue with that is I did not get the role in filter.'
So Do SpringSecurityHolder will work inside Filter.
I have also read about the ApplicationListerner which take Event.
I have return the code but I dont know how to direct from inside the listerner class
import java.util.List;
import org.springframework.context.ApplicationListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.session.HttpSessionDestroyedEvent;
public class SessionTimeoutHandler implements ApplicationListener<HttpSessionDestroyedEvent>{
#Override
public void onApplicationEvent(HttpSessionDestroyedEvent event) {
List<SecurityContext> lstSecurityContext = event
.getSecurityContexts();
for (SecurityContext securityContext : lstSecurityContext)
{
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authList = (List<GrantedAuthority>) authentication
.getAuthorities();
String userRole = authList.get(0).getAuthority();
if(userRole.equals("ROLE_ADMIN")){
}else if(userRole.equals("ROLE_EXPERT")){
}else{
}
}
}
}
Please help me out How will I will be able to redirect the page.
Thanks for the help
There really isn't a good way to determine what role the user is in once the HTTP session expires because once it expires the user information is gone.
You cannot do a redirect from a ApplicationListener because a session may expire when the users browser is not making a request (we cannot push information to the browser unless there is a connection open).
The best solution I can give you is to set a cookie that indicates which role the user is in. The cookie would outlive the session and then you can perform a redirect to the appropriate log in page based on the cookie.
Of course this fails if multiple different types of users are using the same computer because they share the same cookies.

django-facebook does not login facebook test user

I am creating a web app that allows users to register using their Facebook account. I am using django-facebook to do the authentication / registration of new users. I am trying what I think is the simplest setup, using django registration instead of userena. Everything works well when I use my own Facebook account: I am asked to confirm that I allow the app to have access to my profile, a new account is created in the auth_user table and I am logged in.
However, when I am logged in into Facebook as a test user, I confirm that I allow the app and then I am redirected to facebook/connect/?facebook_login=1&attempt=1&code=AQBM0-z......
The new account is not created.
Here are my relevant settings:
TEMPLATE_CONTEXT_PROCESSORS = (
'django_facebook.context_processors.facebook',
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = (
'django_facebook.auth_backends.FacebookBackend',
'django.contrib.auth.backends.ModelBackend',
)
FACEBOOK_APP_ID = NNN
FACEBOOK_APP_SECRET = NNNN
FACEBOOK_REGISTRATION_BACKEND ='django_facebook.registration_backends.FacebookRegistrationBackend'
AUTH_PROFILE_MODULE = 'django_facebook.FacebookProfile'
It seems like the whole problem is that django-facebook removes the long emails from the facebook data. This makes the auth not be able to create an account.
I just commented out the following lines in api.py
if len(user_data.get('email', '')) > 75:
#no more fake email accounts for facebook
del user_data['email']

Resources