Ejemplo n.º 1
0
    def post(cls):
        try:
            user = user_schema.load(request.get_json())
        except ValidationError as err:
            return err.messages, 400

        if UserModel.find_by_username(user['username']):
            return {"msg": "User Already Exists"}, 400

        if UserModel.find_by_email(user['email']):
            return {"msg": "This email already has a registered account."}, 400

        new_user = UserModel(**request.get_json())
        try:
            new_user.register()
            print("User Registered...")
            token = generate_link_token(user['email'])
            UserModel.send_confirmation_email(token, user['email'],
                                              user['username'])
        except:
            return {'msg': "Error Performing Request!!"}, 500

        return {
            'msg':
            "Confirmation Link has been sent to you Email. Please Activate."
        }, 201
Ejemplo n.º 2
0
    def post(self):
        args = self.reqparse.parse_args()

        try:
            user = UserModel.find_by_email(args.email)

            if not user:
                return {'message': 'Error invalid email or password'}, 401

            if not user.active:
                return {'message': 'Please confirm your account'}, 403

            authorized = user.check_password(args.password)

            if not authorized:
                return {'message': 'Error invalid email or password'}, 401

            access_token = create_access_token(
                identity=user.email, expires_delta=timedelta(days=7))
            refresh_token = create_refresh_token(identity=user.email)

            return {'access_token': access_token,
                    'refresh_token': refresh_token,
                    'user_id': user.id}
        except Exception as e:
            raise e
            return {'message': 'Error invalid email or password'}, 401
    def get(cls):
        """
        Accesses user data and logs user in with email
        Output: Access and Refresh token and Calendar Access token
        """
        try:
            response = google.authorized_response()
        except:
            return {"msg": request.args["error"]}

        g.token_access = response['access_token']
        user = google.get('userinfo', token=g.token_access)

        try:
            google_email = user.data['email']
        except:
            return {
                'msg': "User of this account does not exist in database"
            }, 400

        user = UserModel.find_by_email(email=google_email)
        access_token = create_access_token(identity=str(user.id), fresh=True)
        refresh_token = create_refresh_token(str(user.id))

        return {
            'access_token': access_token,
            'refresh_token': refresh_token,
            'calendar_access': g.token_access
        }, 200
Ejemplo n.º 4
0
    def put(self):
        args = self.reqparse.parse_args()

        try:
            email = serializer.loads(args.token, salt=salt, max_age=7200)
        except SignatureExpired as e:
            return {'message': 'Token expired try forgot password'}, 401
        except BadTimeSignature as e:
            return {'message': 'Unknown error try forgot password'}, 400
        except BadSignature as e:
            return {'message': 'Invalid token try forgot password'}, 422

        try:
            user = UserModel.find_by_email(email)

            if not user:
                return {'message': 'Email address was not found'}, 404

            user.password = args.password
            user.hash_password()
            user.update_user()

            return {'message': 'Successfully updated password'}
        except Exception as e:
            raise
Ejemplo n.º 5
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_email(data['email']):
            return {"message": "User with that email already exists."}, 400

        user = UserModel(**data)
        user.save_to_db()

        return {"message": "User created successfully."}, 201
Ejemplo n.º 6
0
def password_forget(email):
    user = UserModel.find_by_email(email)
    if user:
        try:
            print("request for password-reset")
            token = generate_link_token(email)
            UserModel.send_pwd_reset_link(token, user.username, email)
            return "A password reset link has been sent to your email.", 200
        except:
            return "Internal Server Error. Error Sending Email Address.", 500
    return 'User related to this email has not been found!', 404
Ejemplo n.º 7
0
def activate_account():
    user = UserModel.find_by_email(request.get_json()['email'])
    if not user:
        return {
            'msg': "User account related to this email address, is not found."
        }, 404
    token = generate_link_token(user.email)
    UserModel.send_confirmation_email(token, user.email, user.username)
    return {
        'msg': "An Activation Link has been sent to your email Address."
    }, 200
Ejemplo n.º 8
0
    def post(self):
        data = parser.parse_args()
        current_user = UserModel.find_by_email(
            data['email'])  # GET USER DATA BY EMAIL

        if not current_user:
            return {'message': 'User {} doesn\'t exist'.format(data['name'])}

        if UserModel.verify_hash(data['password'], current_user.password):
            return {'message': 'Logged in as {}'.format(current_user.name)}
        else:
            return {'message': 'Wrong credentials'}
Ejemplo n.º 9
0
 def post(self):
     data = UserRegister.parser.parse_args()
     if UserModel.find_by_email(data['email']):
         return printResponse(
             {"message": "A user with that email already exists"}, 400)
     data['created_at'] = datetime.now()
     user = UserModel(**data)
     user.hash_password()
     user.save_to_db()
     return printResponse(
         {
             "message": "User created successfully.",
             "id": user._id
         }, 201)
Ejemplo n.º 10
0
def confirm_email(token):
    try:
        email = confirm_token(token)
    except:
        return "The Confirmation Link has been invalid or expired."
    if not email:
        return "The Confirmation Link has been expired.\nIf you account has not confirmed yet, try to log in to get confirmation link"
    user = UserModel.find_by_email(email)
    if not user:
        return "User Not Found"
    if user.status == "Active":
        return "Your account already confirmed and active."
    else:
        UserModel.activate_account(user.id)
        return render_template('activate.html')
Ejemplo n.º 11
0
    def post(self):
        data = _login_parser.parse_args()
        user = UserModel.find_by_email(data['email'])
        print(user)
        if user and bcrypt.checkpw(data['password'].encode('utf8'),
                                   user.hashedPassword.encode('utf8')):
            # this is the identity function
            access_token = create_access_token(identity=user.id, fresh=True)
            refresh_token = create_refresh_token(user.id)
            return {
                'access_token': access_token,
                'refresh_token': refresh_token
            }, 200

        return {"message": "Invalid Credentials!"}, 401
Ejemplo n.º 12
0
    def post(self):
        data = _register_parser.parse_args()
        hashedPassword = bcrypt.hashpw(data.password.encode('utf8'),
                                       bcrypt.gensalt(10))
        data.hashedPassword = hashedPassword.decode('utf8')
        data.pop('password', 0)
        print(hashedPassword)
        print(data)
        if UserModel.find_by_email(data['email']):
            return {"message": "A user with that email already exists"}, 400
        user = UserModel(**data)
        print(user)
        user.save_to_db()

        return {"message": "User created successfully."}, 201
Ejemplo n.º 13
0
def reset_password(token):
    try:
        email = confirm_token(token, expiration=600)  # ! expired in 10 minutes
    except:
        return "The reset-password link is invalid or expired."
    if not email:
        return "The reset-password link is expired. Try to request new one."
    user = UserModel.find_by_email(email)
    if user and request.method == 'GET':
        return render_template('reset_pwd.html', username=user.username)
    if request.form['reset'] == 'Reset':
        if request.form['password'] == request.form['confirm_pwd']:
            password = request.form['password']
            return password_reset(user.id, password)
        else:  # If passwords doesn't match. Alert User
            flash("Passwords don't match!")
            return render_template('reset_pwd.html', username=user.username)
Ejemplo n.º 14
0
    def post(self):
        args = self.reqparse.parse_args()

        try:
            user = UserModel.find_by_email(args.email)

            if not user:
                return {'message': 'Email address was not found'}, 404

            result = send_reset_password_mail(user)

            if not result:
                return {'message': 'Error please try again'}, 500

            return {'message': 'Please check your inbox'}
        except Exception as e:
            raise
Ejemplo n.º 15
0
    def post(cls):
        try:
            body = request.get_json()
            user = user_schema.load(body)
            
            if UserModel.find_by_username(user.username):
                return {'msg': 'Username {} already exists'.format(user.username)}, 404

            if UserModel.find_by_email(user.email):
                return {'msg': 'Email {} already exists'.format(user.email)}, 404
            
            user.save_to_data()
            user.send_confirmation_email()
            user.sms()
            return {'msg': 'User has been added to database. Verification pending.'}, 200

        except Exception as e:
            return {'msg':str(e)}, 500
Ejemplo n.º 16
0
 def get(cls):
     try:
         credentials = {
             'email': request.args.get('username'),
             'password': request.args.get('password')
         }
         data = user_schema.load(credentials)
     except ValidationError as err:
         return err.messages, 400
     user = UserModel.find_by_email(data["email"])
     if user and check_password_hash(user.password, data['password']):
         access_token = create_access_token(identity=user.id, fresh=True)
         refresh_token = create_refresh_token(user.id)
         return {
             "accessToken": access_token,
             "refreshToken": refresh_token,
             "success": True
         }, 200
     return {"message": CREDENTIAL_ERROR}, 401
Ejemplo n.º 17
0
 def post(self):
     data = UserLogin.parser.parse_args()
     user = UserModel.find_by_email(data['email'])
     if user == None:
         return printResponse({"message": "User doesnt exsist"}, 400)
     authorized = user.check_password(data['password'])
     if not authorized:
         return printResponse({"message": "Email or password incorrect"},
                              401)
     expires = timedelta(hours=12)
     access_token = create_access_token(identity=str(user._id),
                                        expires_delta=expires)
     return printResponse(
         {
             "message": "verified",
             "id": user._id,
             "username": user.username,
             "email": user.email,
             "access_token": access_token,
         }, 200)
Ejemplo n.º 18
0
    def post(self):
        data = parser.parse_args()
        current_user = UserModel.find_by_email(data['email'])

        if not current_user:
            return {
                'message': 'Email {} doesn\'t exist'.format(data['email'])
            }, 422

        if UserModel.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(identity=data['email'])
            refresh_token = create_refresh_token(identity=data['email'])
            return {
                'message': 'Logged in as {}'.format(current_user.email),
                'access_token': access_token,
                'refresh_token': refresh_token,
                'user': current_user,
            }, 200
        else:
            return {'message': 'Invalid credentials'}, 422
Ejemplo n.º 19
0
    def post(self):
        parser.add_argument('name', help='name filed required', required=True)
        parser.add_argument('phone',
                            help='phone field required',
                            required=True)
        parser.add_argument('gender',
                            help='gender field required',
                            required=True)
        parser.add_argument('designation',
                            help='designation field required',
                            required=True)
        parser.add_argument('role', help='role field required', required=True)

        data = parser.parse_args()

        if UserModel.find_by_email(data['email']):
            return {
                'message':
                'User {} already exists with this {}'.format(
                    data['name'], data['email'])
            }

        new_user = UserModel(
            name=data['name'],
            email=data['email'],
            password=UserModel.generate_hash(
                data['password']),  #FOR HASH PASSWORD CALL GENERATE HAS METHOD
            phone=data['phone'],
            gender=data['gender'],
            designation=data['designation'],
            role=data['role'])
        try:
            new_user.save_to_db()
            access_token = create_access_token(identity=data['email'])
            return {
                'message':
                ' {} data created successfully'.format(data['name']),
                'access_token': access_token,
            }
        except:
            return {'message': 'Something went wrong'}, 500
Ejemplo n.º 20
0
    def post(self):
        try:
            data = user_schema.load(request.get_json())
        except ValidationError as err:
            return err.messages, 400

        if UserModel.find_by_email(data["email"]):
            return {"message": "Email already used!"}

        data['password'] = generate_password_hash(data['password'])
        user = UserModel(**data)
        user.save_to_db()
        access_token = create_access_token(identity=user.id, fresh=True)
        refresh_token = create_refresh_token(user.id)

        return {
            "accessToken": access_token,
            "refreshToken": refresh_token,
            "message": "User created succesfully!",
            'success': True,
        }, 201
Ejemplo n.º 21
0
    def post(self):
        data = parser.parse_args()

        if UserModel.find_by_email(data['email']):
            return {
                'message': 'User {} already exists'.format(data['email'])
            }, 422

        new_user = UserModel(email=data['email'],
                             password=UserModel.generate_hash(
                                 data['password']))

        try:
            new_user.save_to_db()
            access_token = create_access_token(identity=data['email'])
            refresh_token = create_refresh_token(identity=data['email'])
            return {
                'message': 'User {} was created'.format(data['email']),
                'access_token': access_token,
                'refresh_token': refresh_token
            }, 201
        except:
            return {'message': 'Something went wrong'}, 500
Ejemplo n.º 22
0
    def get(cls):
        """
        Accesses user data and logs user in with email
        Output: Access and Refresh token
        """
        try:
            response = github.authorized_response()
            print(response)
        except:
            return {"msg": request.args["error"]}

        g.access_token = response['access_token']
        github_user = github.get('user', token=g.access_token)

        try:
            github_username = github_user.data['login']
            github_email = github_user.data['email']

            if github_email is None:
                return {
                    'msg':
                    "Your email has not been linked to your Github account. Cannot login"
                }, 400

        except:
            return {
                'msg': "User of this account does not exist in database"
            }, 400

        user = UserModel.find_by_email(email=github_email)
        access_token = create_access_token(identity=str(user.id), fresh=True)
        refresh_token = create_refresh_token(str(user.id))

        return {
            'access_token': access_token,
            'refresh_token': refresh_token
        }, 200
Ejemplo n.º 23
0
    def post(self):
        args = self.reqparse.parse_args()

        try:
            email = serializer.loads(args.token, salt=salt, max_age=7200)
        except SignatureExpired as e:
            return {'message': 'Token expired contact support'}, 401
        except BadTimeSignature as e:
            return {'message': 'Unknown error contact support'}, 400
        except BadSignature as e:
            return {'message': 'Invalid token contact support'}, 422

        try:
            user = UserModel.find_by_email(email)

            if not user:
                return {'message': 'Email address was not found'}, 404

            user.active = True
            user.update_user()

            return {'message': 'Successfully activated your account'}
        except Exception as e:
            raise