def post(self):
        '''Accepts a username and password to create a new token'''
        args = login_post.parse_args()
        userData = userModel.getByUsername(args['username'])
        expiration = datetime.datetime.utcnow() + datetime.timedelta(days=30)

        if bcrypt.checkpw(args['password'].encode('utf8'), userData['password']):

            '''delete any existing tokens if any'''
            deletedTokensCount = userModel.delete_authentication_token(userData['_id'])
            if deletedTokensCount != 0:
                print(deletedTokensCount, "Tokens removed")

            key = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
            token = create_token(str(userData['_id']), key).decode('utf8')

            '''Adding expiration to expand functionality for the future'''

            tokenObj = {
                'user_id': userData['_id'],
                'authentication_token': token,
                'salt': key,
                'expires': expiration
            }
            insertedToken = userModel.createAuthenticationToken(tokenObj)
            if insertedToken == {}:
                api.abort(500, 'Internal Server Error')
                response = {'user_id': str(userData['_id']), 'authentication_token': token}
                '''Since mongo is fire and forget, use the id and token generated before insertion'''
                return response
            else:
                api.abort(401, 'username or password does not match')
Example #2
0
    def post(self):
        todo = api.payload
        if not api.payload or 'title' not in api.payload.keys():
            api.abort(401, "Todo need at least a title" + str(api.payload))
        todo_obj = models.Todo(**todo)
        db.session.add(todo_obj)
        db.session.commit()
        db.session.refresh(todo_obj)

        return todo_obj.to_dict(), 201
 def delete(self, id):
     '''Delete a User with Given ID'''
     checkResult = UserModel.get_by_id_string(self, id)
     if (checkResult is None):
         return {"No Specified User Found" : "Equal to Deleted"}, 200
     delete_one_result = UserModel.delete_by_id(self, id)
     deleted_count = delete_one_result.deleted_count
     if (deleted_count == 0):
         api.abort(500, 'Cannot Delete the Specified User')
     return {"Specified User Deleted" : "Done"}, 200
Example #4
0
    def put(self, todo_id):
        """Update a task given its identifier"""

        todo_obj = models.Todo.query.get(todo_id)

        if not todo_obj:
            api.abort(404, f"Todo {todo_id} doesn't exist")

        todo_obj.title = api.payload['title']
        if 'complete' in api.payload:
            todo_obj.complete = api.payload['complete']
        db.session.commit()
        return todo_obj.to_dict(), 200
 def put(self, id): 
     '''Update an Existinng User'''
     #check whether it's existed or not
     checkResult = UserModel.get_by_id_string(self, id)
     if (checkResult is None):
         api.abort(404, 'User Not Found')
     args = user_parser.parse_args()
     incomingUserData = args['data']
     upserted_res = UserModel.update_user(self, id, incomingUserData)
     if upserted_res == {}:
         api.abort(500, 'Cannot Updated the User')
     res = UserModel.get_by_id_string(self, id)
     return res, 
    def post(self):
        '''Add a New User'''
        args = user_post_parser.parse_args()
        incomingUserData = args['data']

        # Hashing Password before store into the db!
        hashed_password = bcrypt.hashpw(str(args['password']).encode('utf8'), bcrypt.gensalt())
        incomingUserData['password'] = hashed_password
        insert_one_result = UserModel.create_user(self, incomingUserData)
        if isinstance(insert_one_result, dict) and 'error' in insert_one_result.keys():
            api.abort(500, newUser['error'])
        # Have not confirmed the usage of insertOneResult.key() !!!
        if insert_one_result == {}:
            api.abort(500, 'Internal Server Error: Can Not Create the User')
        user_inserted_id = insert_one_result.inserted_id

        #create authentication token for the user
        token = create_token(str(user_inserted_id), key).decode("utf-8")
        key = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
        expiration = datetime.datetime.utcnow() + datetime.timedelta(days=30)

        tokenObj = {
            'user_id': user_inserted_id,
            'authentication_token': token,
            'salt': key,
            'expires': expiration 
        }
        # create it/put it into database
        auth_res = UserModel.create_authentication_token(tokenObj)
        if auth_res == {}:
            api.abort(500, 'Internal Server Error: Can not create authentication token')

        # create verification token and send email to verify user
        verificationToken = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
        verificationTokenObj = {
            'user_id': user_inserted_id,
            'verification_token': str(verificationToken)
        }
        veri_res = UserModel.create_email_verfication_token(verificationTokenObj)
        if veri_res == {}:
            api.abort(500, 'Internal server error: Can not create verification token')
        
        emailResponse = sendEmail(CONFIG['email'], args['email'], 'Verify email address', CONFIG['host']+'user/verify?token='+verificationToken)
        if emailResponse == {}:
            api.abort(500, 'Email could not be delivered')
        # expose only user_id and user authentication toekn 
        # not necessary return all user's information
        response = {'user_id': str(user_inserted_id), 'authentication_token': token}
        return response, 200
    def post(self):
        args = assistance_parser.parse_args()
        event = Event.query.get_by_tag(args.event)
        if not event.hasAvailability():
            api.abort(400, "The event haven't availability")

        newAssistance = Assistance(
            eventTag = args.event,
            event = event.getAppearanceAssistance(),
            user = currentUser().username,
            requirements = map(lambda req: Requirement(name=req["name"],quantity=req["quantity"]), args.requirements)
        )
        newAssistance.save()
        mailService.assistance(newAssistance, currentUser())
        log.info("Crea una Asistencia con: {'evento':'%s'}" % newAssistance.event)
        return newAssistance, 201    
Example #8
0
 def get(self, tag):
     log.info("Otorga el Evento con: {'tag':'%s'}" % tag)
     event = Event.query.get_by_tag(tag)
     event.hasAssistance = False
     event.isOwner= False
     user = currentUser()
     event.soldOut = not event.hasAvailability()
     if event.hasAccess(user) :
         if isLogged():
             assistance = Assistance.query.get_by_eventTag_and_user(event.tag, user)
             event.hasAssistance = assistance is not None
             event.requirementMissing = event.lackRequirements()
             event.isOwner = event.owner.username == user.username
         return event
     else:
         log.warning("Se requiere Autorizacion para este recurso.")
         api.abort(401, "Authorization Required")
    def post(self):
        '''kills the access token'''
        token = logout_post.parse_args()['x-access-token']
        user_id = logout_post.parse_args()['user_id']
        killedToken = userModel.delete_authentication_token(token)
        if killedToken == {}:
            return api.abort(404, 'Token not found')

        return response_success
    def post(self):
        args = assistance_parser.parse_args()
        event = Event.query.get_by_tag(args.event)
        if not event.hasAvailability():
            api.abort(400, "The event haven't availability")

        newAssistance = Assistance(
            eventTag=args.event,
            event=event.getAppearanceAssistance(),
            user=currentUser().username,
            requirements=map(
                lambda req: Requirement(name=req["name"],
                                        quantity=req["quantity"]),
                args.requirements))
        newAssistance.save()
        mailService.assistance(newAssistance, currentUser())
        log.info("Crea una Asistencia con: {'evento':'%s'}" %
                 newAssistance.event)
        return newAssistance, 201
    def post(self):
        '''Reset password'''
        old_password = reset_post.parse_args()['old_password']
        new_password = reset_post.parse_args()['new_password']
        # Here toekn is same as the temp_password
        tempPasswordLookup = userModel.searchEmailVerificationToken(old_password)
        if tempPasswordLookup == {}:
            api.abort(401, "Password not found")

        #update verification data for future reset code
        delete_email_verification_token(self, old_password)
        newPasswordObj = {
                'user_id': user_id,
                'verification_token': new_password
            }
        insertedVerificationToken = userModel.create_email_verfication_token(newPasswordObj)
        if insertedVerificationToken == {}:
            api.abort(500, 'Internal server error')

        hashedPassword = bcrypt.hashpw(new_password.encode('utf8'), bcrypt.gensalt())

        userData = userModel.get_by_id_string(tempPasswordLookup['user_id'])

        if userData == {}:
            api.abort(404, 'User Not found')

        userData['password'] = hashedPassword

        userId = ''
        if '_id' in userData.keys():
            userId = userData['_id']
            del userData['_id']
        else:
            api.abort(500, 'Internal server error')

        updatedUserData = userModel.update_user(userId, userData)

        if (updatedUserData == {}):
            api.abort(404, 'User Not found')

        return response_success
    def post(self):
        '''Send email to reset password'''
        user_id = forgot_post.parse_args()['user_id']
        email = forgot_post.parse_args()['email']

        user_output = userModel.getOne(user_id)

        if email == user_output['email']:
            #what if this delete is not succssful?
            delete_email_verification_token_by_id(self, user_id)
            tempPassword = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)])
            tempPasswordObj = {
                'user_id': user_id,
                'verification_token': tempPassword
            }
            insertedVerificationToken = userModel.create_email_verfication_token(tempPasswordObj)
            if insertedVerificationToken == {}:
                api.abort(500, 'Internal server error')
            
            #if temp password has been updated 
            


            '''send email with temp password'''
            emailResponse = sendEmail('*****@*****.**', email, 'New Password', tempPassword)
            if emailResponse == {}:
                api.abort(500, 'Internal server error')
        else:
            api.abort(404, "Email not found")

        return response_success
    def get(self):
        '''Verify email'''
        token = verify_get.parse_args()['token']
        verificationTokenLookup = userModel.search_email_verification_token(token)
        if verificationTokenLookup == {}:
            api.abort(404, 'Token not found')

        userData = userModel.get_by_id_string(verificationTokenLookup['user_id'])
        userData['email_verified'] = True
        del userData['_id']

        updatedUserData = userModel.update_user(verificationTokenLookup['user_id'], userData)
        if updatedUserData == {}:
            api.abort(404, 'User not found')

        deleteVerificationToken = userModel.delete_email_verification_token(verificationTokenLookup['verification_token'])
        if deleteVerificationToken == {}:
            api.abort(500, 'Internal Server Error')

        return response_success
Example #14
0
 def get(self, id):
     for todo in self.todos:
         if todo['id'] == id:
             return todo
     api.abort(404, "Todo {} doesn't exist".format(id))
Example #15
0
def error_handler(e):
    api.abort(401, "Authorization Required")
 def get(self, id):
     '''Fetch a User with Given ID'''
     target_user = UserModel.get_by_id_string(self, id)
     if target_user == {}:
         api.abort(404, 'User Not Found')
     return target_user, 200