示例#1
0
 def generate_new_link(self, request):
     """ Generate new link after expiry """
     email = request.data.get('email')
     req_type = request.data.get('req_type')
     serializer = SecurityLinkSerializer(data=request.data)
     if serializer.is_valid():
         try:
             get_object(User, email, "User")
             if req_type == 'activate':
                 path = '/api/v1/accounts/activate/'
                 subject = 'Grind - Activate your account'
                 template = 'confirm_account.html'
             else:
                 path = '/api/v1/accounts/send-reset/'
                 subject = 'Grind - Password Reset'
                 template = 'password_reset.html'
             send_account_email(request, subject, path, template)
             return custom_reponse(
                 'succes',
                 200,
                 message="A new link has been sent to your email")
         except (SMTPException, IndexError, TypeError):
             return custom_reponse('error',
                                   400,
                                   message='An error occured, please retry')
     return custom_reponse('error',
                           400,
                           serializer=serializer,
                           error_type='bad_request')
示例#2
0
 def login(self, request):
     serializer = LoginSerializer(data=request.data,
                                  context={'request': request})
     if serializer.is_valid():
         user = serializer.validated_data.get('user')
         auth_login(request, user)
         return custom_reponse('succes',
                               200,
                               token=user.token,
                               message='Login success')
     return custom_reponse('error',
                           400,
                           serializer=serializer,
                           message='login_invalid')
示例#3
0
 def update(self, request):
     """ Change password"""
     passwords = request.data
     user = request.user
     serializer = self.serializer_class(data=passwords,
                                        context={'request': request})
     if serializer.is_valid():
         user.set_password(passwords.get('new_password'))
         user.save()
         return custom_reponse('succes',
                               200,
                               message='Password updated successfully')
     return custom_reponse('error',
                           400,
                           serializer=serializer,
                           error_type='bad_request')
示例#4
0
 def admin_delete(self, request, pk):
     """ Delete user by ID """
     if request.user.admin:
         try:
             User.objects.get(pk=pk).delete()
             return custom_reponse(
                 'success',
                 204,
                 message='User ID:{} deleted successfully'.format(pk))
         except User.DoesNotExist:
             return custom_reponse(
                 'error', 404, message='User ID:{} not found'.format(pk))
     return custom_reponse(
         'error',
         403,
         message='You don\'t have permission to perform this action')
示例#5
0
 def post(self, request, **kwargs):
     """
     POST: /api/v1/ouath/twitter/login/
     Register or login user if exists
     Returns: user token and/or user data
     """
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     access_token_key = serializer.data.get('access_token')
     access_token_secret = serializer.data.get('access_token_secret')
     try:
         consumer_key = settings.TWITTER_CONSUMER_KEY
         consumer_secret = settings.TWITTER_CONSUMER_SECRET
         api = twitter.Api(
             consumer_key=consumer_key,
             consumer_secret=consumer_secret,
             access_token_key=access_token_key,
             access_token_secret=access_token_secret
         )
         user_info = api.VerifyCredentials(include_email=True)
         user_info = user_info.__dict__
         user_info = get_user_info(user_info)
     except:
         return custom_reponse('error', 400, message='Invalid token.')
     twitter_social_authentication = SocialAuth()
     return twitter_social_authentication.social_login_signup(
         user_info, **kwargs)
示例#6
0
    def retrieve(self, request, username):
        """ Return user profile """
        profile = get_object(User, username, "User")
        serializer = self.serializer_class(profile,
                                           context={'request': request})

        return custom_reponse('success', 200, serializer=serializer)
示例#7
0
 def activate(self, request, uid, token):
     """ Get request for activating user account """
     try:
         uid = force_text(urlsafe_base64_decode(uid))
         user = get_object(User, uid, "User")
         decoded_token = jwt_auth.decode_token(token)
         now = int(datetime.now().strftime('%s'))
         if now > decoded_token['exp']:
             return custom_reponse('error', 400, message='Link has expired')
         else:
             if user is not None and decoded_token['email'] == user.email:
                 user.active = True
                 user.save()
                 # TODO: update redirect url to web-app login
                 return HttpResponseRedirect(
                     redirect_to='http://127.0.0.1:8000/?status=success')
             else:
                 return custom_reponse(
                     'error', 400, message='Activation link is invalid!')
     except (TypeError, ValueError, OverflowError):
         return custom_reponse('error', 400, message='An error occured')
示例#8
0
 def password_reset_update(self, request, uid, token):
     """ Update the new password to db """
     decoded_token = jwt_auth.decode_token(token)
     now = int(datetime.now().strftime('%s'))
     if now > decoded_token['exp']:
         # TODO: add generate new link endpoint
         return custom_reponse('error', 400, message='Link has expired')
     serializer = PasswordResetSerializer(data=request.data,
                                          context={'request': request})
     if serializer.is_valid():
         uid = force_text(urlsafe_base64_decode(uid))
         user = get_object(User, uid, "User")
         password = request.data.get('password')
         user.set_password(password)
         user.save()
         return custom_reponse('success',
                               200,
                               message='Password successfully updated')
     return custom_reponse('error',
                           400,
                           serializer=serializer,
                           error_type='bad_request')
示例#9
0
 def send_reset_email(self, request):
     """ Send password reset email """
     serializer = ResetEmailSerializer(data=request.data)
     email = request.data.get('email')
     if serializer.is_valid():
         try:
             get_object(User, email, "User")
             send_account_email(request, 'Grind - Password Reset',
                                '/api/v1/accounts/send-reset/',
                                'password_reset.html')
             # TODO: to update link to web-app reset password page
             return custom_reponse(
                 'succes',
                 200,
                 message="A reset link has been sent to your email")
         except (SMTPException, IndexError, TypeError):
             return custom_reponse('error',
                                   400,
                                   message='An error occured, please retry')
     return custom_reponse('error',
                           400,
                           serializer=serializer,
                           error_type='bad_request')
示例#10
0
 def create(self, request):
     """ Register new user and send activation email"""
     serializer = UserSerializer(data=request.data,
                                 context={'request': request})
     if serializer.is_valid():
         try:
             send_account_email(request, 'Grind - Activate your account',
                                '/api/v1/accounts/activate/',
                                'confirm_account.html')
         except (SMTPException, IndexError, TypeError) as e:
             return custom_reponse('error',
                                   400,
                                   message='An error occured, please retry',
                                   error_type='email_error')
         serializer.save()
         return custom_reponse(
             'success',
             201,
             serializer=serializer,
             message=
             'Registered successfully, check your email to activate your account.'
         )
     return custom_reponse('error', 400, serializer=serializer)
示例#11
0
 def update(self, request):
     """ Update user profile """
     user_data = request.data
     serializer_data = {
         'email': user_data.get('email', request.user.email),
         'user_type': user_data.get('user_type', request.user.user_type),
         'profile': {
             'title':
             user_data.get('title', request.user.profile.title),
             'bio':
             user_data.get('bio', request.user.profile.bio),
             'image':
             user_data.get('image', request.user.profile.image),
             'phone':
             user_data.get('phone', request.user.profile.phone),
             'location':
             user_data.get('location', request.user.profile.location),
             'address_1':
             user_data.get('address_1', request.user.profile.address_1),
             'address_2':
             user_data.get('address_2', request.user.profile.address_2),
         }
     }
     serializer = self.serializer_class(request.user,
                                        data=serializer_data,
                                        partial=True,
                                        context={'request': request})
     if serializer.is_valid():
         serializer.save()
         return custom_reponse('succes',
                               200,
                               message='Profile updated successfully',
                               serializer=serializer)
     return custom_reponse('error',
                           400,
                           serializer=serializer,
                           error_type='bad_request')
示例#12
0
 def post(self, request, **kwargs):
     """
     POST: /api/v1/ouath/google/login/
     Register or login user if exists
     Returns: user token and/or user data
     """
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     access_token = serializer.data.get('access_token')
     try:
         user_info = id_token.verify_oauth2_token(
             access_token, requests.Request())
         user_info = get_user_info(user_info)
     except:
         return custom_reponse('error', 400, message='Invalid token.')
     google_auth = SocialAuth()
     return google_auth.social_login_signup(user_info, **kwargs)
示例#13
0
 def post(self, request, **kwargs):
     """
     POST: /api/v1/ouath/facebook/login/
     Register or login user if exists
     Returns: user token and/or user data
     """
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     access_token = serializer.data.get('access_token')
     try:
         facebook_user = facebook.GraphAPI(access_token=access_token)
         user_info = facebook_user.get_object(
             id='me', fields='name, id, email, first_name, last_name')
     except:
         return custom_reponse('error', 400, message='Invalid token.')
     facebook_auth = SocialAuth()
     return facebook_auth.social_login_signup(
         user_info, **kwargs)
示例#14
0
 def social_login_signup(self, user_info, **kwargs):
     """
     If user exists, authenticate user with their `social account` info
     else register user using their `social accounts`
     info.
     Returns: API access token and/or user data.
     """
     try:
         user = User.objects.get(email=user_info.get('email'))
         token = user.token
         return custom_reponse('success',
                               200,
                               toke=token,
                               message='Logged in successfully.')
     except User.DoesNotExist:
         password = User.objects.make_random_password()
         user = User(username=str(user_info.get('first_name')) +
                     str(uuid.uuid1().int)[:3],
                     email=user_info.get('email'),
                     first_name=user_info.get('first_name'),
                     last_name=user_info.get('last_name'),
                     active=True)
         user.set_password(password)
         user.save()
         user_details = {
             'id': user.id,
             'username': user.username,
             'email': user.email,
             'first_name': user.first_name,
             'last_name': user.last_name
         }
         token = user.token
         return Response(
             {
                 'status': 'success',
                 'token': token,
                 'data': user_details,
                 'message': 'Account created successfully '
             },
             status=status.HTTP_201_CREATED)
示例#15
0
 def logout(self, request):
     auth_logout(request)
     return custom_reponse('success',
                           204,
                           message='You have been logged out')
示例#16
0
 def list(self, request):
     """ Return all users """
     serializer = self.serializer_class(self.queryset,
                                        many=True,
                                        context={'request': request})
     return custom_reponse('success', 200, serializer=serializer)
示例#17
0
 def delete(self, request):
     request.user.delete()
     return custom_reponse('success', 204, message='Deleted successfully')