Ejemplo n.º 1
0
def sign_up():
    body = request.get_json()
    user = User(**body).save()
    user.hash_password()
    user.save()
    id = user.id
    return {'id': str(id)}, 200
Ejemplo n.º 2
0
async def signup(form_data: EmailPasswordForm, request: Request,
                 background_tasks: BackgroundTasks):
    try:
        try:
            user = User(email=form_data.username, password=form_data.password)
        except NotUniqueError:
            user = User.objects.get(email=form_data.username,
                                    verified=False,
                                    created__lt=datetime.now() -
                                    timedelta(days=1))
            user.password = form_data.password
        if User.objects.count() == 0:
            user.admin = True
        user.hash_password()
        user.save()
        verify_token = create_access_token(str(user.id),
                                           expires_delta=timedelta(days=1))
        send_email_backround(
            background_tasks, 'Verify Your Email', [user.email],
            'verify_email.html', {
                'url':
                f'{request.client.host}:{request.client.port}/login?t={verify_token}',
            })
        # FOR DEBUG PURPOSES
        # TODO: remove in production
        print(request.client.host + ':' + request.client.port + '/login?t=' +
              verify_token)
        return {'id': str(user.id)}
    except DoesNotExist:
        raise UserAlreadyExistsError().http_exception
    except Exception as e:
        raise e
Ejemplo n.º 3
0
	def post(self):
		try:
			body		= request.get_json()
			username	= body.get('username').title()
			email		= body.get('email')
			password	= body.get('password')
			if username is None or password is None or email is None:
				raise ValidationError
			if password != body.get('password2'):
				return {'password': '******'}, 400
			if User.objects(Q(username__iexact=username) or Q(email__iexact=email)).count() > 0:
				raise NotUniqueError
			user = User(username=username, password=password, email=email)
			user.hash_password()
			user.save()

			expires		= timedelta(days=7)
			access_token= create_access_token(identity=str(user.id), expires_delta=expires)
			return  {'type': 'success', 'success': 'Login succesfull.', 'username': user.username, 'token': 'Bearer ' + access_token}, 200
		except (FieldDoesNotExist, ValidationError, ValueError) as e:
			return SchemaValidationError, 400
		except NotUniqueError:
			return EmailAlreadyExistsError, 400
		except Exception as e:
			print(e)
			return InternalServerError, 500
Ejemplo n.º 4
0
def signup():
    try:
        body = request.get_json()
        user = User(**body)

        if len(user.password) < 8:
            response = make_response({
                "status":
                "fail",
                "message":
                "password must be atleast 8 characters long"
            })
            return response

        user.hash_password()
        user.save()
        return {"status": "success", "user": user}, 200

    except ValidationError:
        response = make_response({
            "status": "fail",
            "message": "This is not a valid phone number"
        })
        return response, 400

    except NotUniqueError:
        response = make_response({
            "status": "fail",
            "message": "Account already exists!"
        })
        return response, 409
Ejemplo n.º 5
0
 def post(self):
     body = request.get_json();
     user = User(**body);
     user.hash_password();
     user.save();
     id = user.id
     return {"status":"true",'id': str(id)}, 200
Ejemplo n.º 6
0
 def post(self):
     url = request.host_url + 'verify/'
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         #return {'id': str(id)}, 200
         expires = datetime.timedelta(hours=24)
         access_token = create_access_token(str(id), expires_delta=expires)
         return send_email(
             'Login verification',
             sender='*****@*****.**',
             recipients=[user.email],
             text_body=render_template('auth/login_email.txt',
                                       url=url + access_token),
             html_body=render_template('auth/login_email.html',
                                       url=url + access_token))
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
Ejemplo n.º 7
0
 def post(self):
     body = request.get_json()
     try:
         User.objects.get(email=body.get('email'))
     except DoesNotExist:
         user = User(**body)
         user.hash_password()
         try:
             user.save()
         except ValidationError as e:
             return {'error': str(e)}, 401
         else:
             expires = datetime.timedelta(days=1)
             access_token = create_access_token(identity=str(user.id),
                                                expires_delta=expires)
             now = datetime.datetime.utcnow()
             expires_epoch = (
                 (now + expires) -
                 datetime.datetime(1970, 1, 1)).total_seconds()
             return {
                 'token': access_token,
                 'token_expiry': expires_epoch,
                 'username': user.username,
                 'address': user.address
             }, 200
     else:
         return {'error': 'Email already exists'}, 409
Ejemplo n.º 8
0
 def post(self):
     body = request.get_json()
     user = User(**body)
     user.hash_password()
     user.save()
     id = user.id
     return {'id': str(id)}, 200
Ejemplo n.º 9
0
 def post(self):
     body = request.get_json()
     # TODO: return error if username not unique
     user = User(**body)
     user.hash_password()
     user.save()
     id = user.id
     return {'id': str(id), 'username': user.username, 'groups': user.groups, 'contacts': user.contacts, 'error':''}, 200
Ejemplo n.º 10
0
class UserTestCase(unittest.TestCase):
    def setUp(self):
        app.config.update({
            "TESTING": True,
            "TEMP_DB": True,
            "WTF_CSRF_ENABLED": False,
            "DEBUG": False
        })
        self.app = app.test_client()
        self.assertEqual(app.debug, False)
        db.disconnect()
        db.connect('sample_test')
        User.drop_collection()
        app.register_blueprint(auth_api, url_prefix='/api/auth')
        app.register_blueprint(user_api, url_prefix='/api/user')
        self.supporter = User(username="******",
                              password="******",
                              role="SUPPORTER")
        self.supporter.hash_password()
        self.supporter.save()
        self.user = User(username="******", password="******", role="USER")
        self.user.hash_password()
        self.user.save()

    def test_supporterCanCreateUser(self):
        testUtil.test_help_login(self.app, self.supporter.username,
                                 self.supporter.username)
        response = self.app.post('/api/user/create',
                                 data=json.dumps(
                                     dict(username='******',
                                          password='******',
                                          role='USER')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(200, response.status_code)

    def test_userShouldNotAbleToCreateNewUser(self):
        testUtil.test_help_login(self.app, self.user.username,
                                 self.user.username)
        response = self.app.post('/api/user/create',
                                 data=json.dumps(
                                     dict(username='******',
                                          password='******',
                                          role='USER')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(403, response.status_code)

    def test_userCanViewOtherUserProfile(self):
        testUtil.test_help_login(self.app, self.user.username,
                                 self.user.username)
        response = self.app.get('/api/user/all',
                                content_type='application/json',
                                follow_redirects=True)
        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.json))
Ejemplo n.º 11
0
 def test_loginSuccessWithUPPERCaseUsername(self):
     user = User(username="******", password="******", role="SUPPORTER")
     user.hash_password()
     user.save()
     response = self.app.post('/api/auth/login',
                              data=json.dumps(
                                  dict(username='******', password='******')),
                              content_type='application/json',
                              follow_redirects=True)
     self.assertEqual(200, response.status_code)
Ejemplo n.º 12
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         return {'id': str(user.id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception:
         raise InternalServerError
Ejemplo n.º 13
0
    def post(self):
        try:
            body = request.get_json()
            user = User(**body)
            user.validate()
            user.hash_password()
            user.save()
            return jsonify(user)

        except NotUniqueError as e:
            return "User already exists!", 409
        except ValidationError as e:
            return e.to_dict(), 422
Ejemplo n.º 14
0
    def post(self):
        body = request.get_json()
        # try:
        #User(name=body[])
        if len(body['firstName']) == 0 or len(body['lastName']) == 0 or len(
                body['emailID']) == 0 or len(body['password']) == 0 or len(
                    body['confirmPassword']) == 0:
            return make_response(
                jsonify({
                    "message": "all fields are required",
                    "statusCode": 500
                }))
            # raise FieldsEmpty

        existingUser = User.objects(emailID=body['emailID'])
        if (existingUser):
            return make_response(
                jsonify({
                    "message": "user already exists, try to login",
                    "statusCode": 500
                }))
            # raise UserAlreadyExist

        if len(body['password']) < 6:
            return make_response(
                jsonify({
                    "message": "password is less than 6 characters",
                    "statusCode": 500
                }))
            # raise PasswordIsShort

        if body['password'] != body['confirmPassword']:
            return make_response(
                jsonify({
                    "message": "passwords doesnt match,please check",
                    "statusCode": 500
                }))
            # raise UnAuthorized

        # print("body" + str(body))

    # except:
        print("entered")
        newUser = User(firstName=body['firstName'],
                       lastName=body['lastName'],
                       emailID=body['emailID'],
                       password=body['password'],
                       confirmPassword=body['confirmPassword'])
        newUser.hash_password()
        newUser.save()
        return make_response(jsonify(newUser['emailID'], {"statusCode": 200}))
Ejemplo n.º 15
0
 def post(self):
     try:
         body = request.get_json(force=True)
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {"id": str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         print(e.message, e.args)
Ejemplo n.º 16
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {'id': str(id)}, 200
     except FieldDoesNotExist:
         return errors['SchemaValidationError']
     except NotUniqueError:
         return errors['EmailAlreadyExistsError']
     except Exception as e:
         return errors['InternalServerError']
Ejemplo n.º 17
0
def signup():
    try:
        body = request.get_json(force=True)
        user = User(**body)
        user.hash_password()
        user.save()
        index = user.id
        return {'user_id': str(index)}, 200
    except FieldDoesNotExist:
        return {'message': "Request is missing required fields"}, 400
    except NotUniqueError:
        return {'message': "User with given email address already exists"}, 400
    except Exception as e:
        return {'message': "Something went wrong"}, 500
Ejemplo n.º 18
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         return 'User created!', 201
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         error = Errors("Given e-mail already in use", "email")
         return error.notunique()
     except Exception as e:
         raise InternalServerError
Ejemplo n.º 19
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body,
                     created_at=datetime.now(),
                     last_logged_in=datetime.now())
         user.hash_password()
         user.save()
         id = user.id
         return {'id': str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
Ejemplo n.º 20
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         response = {'id': user.id}
         return Response(json.dumps(response),
                         mimetype="application/json",
                         status=200)
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
Ejemplo n.º 21
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         #admin = Admin.objects.get(id=admin.id).to_json()
         #return Response(admin, mimetype="application/json", status=200)
         return {'id': str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
Ejemplo n.º 22
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {
             'Success': 'You successfully signed up!',
             'id': str(id)
         }, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
Ejemplo n.º 23
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         expires = datetime.timedelta(days=7)
         access_token = create_access_token(identity=str(id),
                                            expires_delta=expires)
         return {'id': str(id), 'token': access_token}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
Ejemplo n.º 24
0
    def post(self):
        try:
            user_dict = dict()
            body = request.get_json()
            user = User(**body)
            user.representation = []
            user.hash_password()
            user.save()
            id = user.id

            return {'id': str(id)}, 200

        except FieldDoesNotExist:
            raise SchemaValidationError
        except NotUniqueError:
            raise EmailAlreadyExistsError
        except Exception as e:
            raise InternalServerError
Ejemplo n.º 25
0
 def post(self):
     body = MultiDict(request.get_json())
     form = RegisterForm(body)
     if User.objects.filter(email=body.get("email")).count() > 0:
         return {'email': ["This email already exists"]}, 400
     if form.validate():
         user = User(**body)
         user.hash_password()
         user.save()
         expires = datetime.timedelta(minutes=20)
         access_token = create_access_token(identity=str(user.id),
                                            expires_delta=expires)
         return {
             "user": json.loads(user.to_json()),
             "access_token": access_token
         }, 200
     else:
         return form.errors, 400
Ejemplo n.º 26
0
    def post(self):
        body = request.get_json()
        fields = ['username', 'password']
        if not fields_are_in(body, fields):
            return {'error': 'Missing a field'}, 400
        if is_empy_or_none(body):
            return {'error': 'A field is empty or None'}, 400
        
        username = body.get('username').strip(' ')
        user = User.objects(username=username).first()
        if user is None:
            new_user = {
                'username': username,
                'password': body.get('password'),
                'nb_followers': 0,
                'nb_following': 0,
                'nb_login': 1,
                'nb_pictures': 0,
                'bio': 'Welcome to mypanda space!!',
                'dates': [str(datetime.now())+ ' longitude: ' + str(body.get('longitude'))+ ' latitude: ' + str(body.get('latitude'))],

            }
            new_user = User(**new_user)
            new_user.hash_password()
            new_user.save()
            expires = timedelta(hours=3)
            access_token = create_access_token(identity=str(new_user.id), expires_delta=expires)
            return {'token': access_token,
                    'bio': new_user.bio}, 200
        authorized = user.check_password(body.get('password'))
        if not authorized:
            return {'error': 'Password does not match username'}, 401
        if authorized:
            user.update(nb_login=user.nb_login + 1)
            user.update(push__dates=str(datetime.now())+' longitude: '+str(body.get('longitude'))+' latitude: '+str(body.get('latitude')))
            expires = timedelta(hours=3)
            access_token = create_access_token(identity=str(user.id), expires_delta=expires)
            return {'token': access_token,
                    'bio': user.bio}, 200
Ejemplo n.º 27
0
def create_user():
    role = get_jwt_claims()['role']
    if role not in ROLE or role == 'USER':
        return jsonify({'message': 'Permission denied'}), 403

    data = request.get_json()
    username = data.get('username', None)
    password = data.get('password', None)
    role = data.get('role', None)
    if username is not None \
            and password is not None \
            and role is not None:
        try:
            if len(username) < 3:
                return jsonify(
                    {'message':
                     'username must greater than 3 characters'}), 400
            nor_username = username.strip().lower()
            if nor_username.find(' ') != -1:
                return jsonify({'message':
                                'username should not have space'}), 400
            if role not in ROLE:
                return jsonify({'message': 'invalid role'}), 400

            user = User(username=nor_username, password=password, role=role)
            user.hash_password()
            user.save()

        except NotUniqueError:
            return jsonify({"ok": False, "message": "User exist"}), 400
        return jsonify({
            'ok': True,
            'message': 'User created successfully!'
        }), 200
    else:
        return jsonify({
            'ok': False,
            'message': 'Bad request parameters!'
        }), 400
Ejemplo n.º 28
0
    def post(self):
        body = request.get_json()
        if body is not None:
            try:
                user = User(**body)
                user.validate()
                user.hash_password()
                user.save()
            except NotUniqueError as nue:
                return {"message": "Email alreay Exists"}, 419
            except ValidationError as ve:
                return {"message": str(ve.errors)}, 420
            except FieldDoesNotExist as fdne:
                return {"message": fdne.args[0]}, 418
            except Exception as e:
                return {"message": "something went wrong"}, 400

            return {"message": "Signup Successful"}, 200
        else:
            return {
                "message": "body should be non empty, valid json object"
            }, 422
Ejemplo n.º 29
0
    def post(self):
        data = request.get_json()
        schema = RegisterSchema()
        try:
            validated_data = schema.load(data)
        except marshmallow.exceptions.ValidationError as error:
            message = "请求错误"
            for msg in error.messages.values():
                message = msg[0]
            resp = {"status": 0, "msg": message, "errors": error.messages}
            return resp, 200

        user = User(**validated_data)
        user.hash_password()
        user.save()
        id = user.id
        return {
            "status": 1,
            "msg": "ok",
            "data": {
                "id": str(id)
            },
        }, 200
Ejemplo n.º 30
0
    def test_cannotLoginWithBlankPasswordOrBlankUsername(self):
        user = User(username="******",
                    password="******",
                    role="SUPPORTER")
        user.hash_password()
        user.save()

        response = self.app.post('/api/auth/login',
                                 data=json.dumps(
                                     dict(username='', password='******')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(401, response.status_code)
        self.assertIn('Username can not be blank',
                      response.json.get('message', None))

        response = self.app.post('/api/auth/login',
                                 data=json.dumps(
                                     dict(username='******', password='')),
                                 content_type='application/json',
                                 follow_redirects=True)
        self.assertEqual(401, response.status_code)
        self.assertIn('Password can not be blank',
                      response.json.get('message', None))