예제 #1
0
def index(request):
    context = {'message' : "Please enter your credentials below"}
    if request.method == 'POST':
        form = UserForm(request.POST)
        username = form.data[u'username']
        password = form.data[u'passwd']
        if u'login' in form.data:
            result = UserModel.login(username, password)
        elif u'adduser' in form.data:
            result = UserModel.add(username, password)
        else:
            result = None # This should never be reached

        if result == UserModel.SUCCESS:
            u = UserModel.objects.get(username = username)
            context['message'] = "User {0} has logged on {1} times".format(u.username, u.count)
            return render(request, 'users/login.html', context )
        elif result == UserModel.ERR_BAD_USERNAME:
            context['message'] = "ADD USER ERROR: Username is " + ("empty" if len(username) == 0 else "too long")
        else:
            context['message'] = errors[result]
    else:
        form = UserForm()
    context['form'] = form
    return render(request, 'users/login.html', context )
예제 #2
0
 def handle(self, *args, **options):
     admin = UserModel(name='admin',
                       pinyin='admin',
                       phone='15116381393',
                       email='*****@*****.**',
                       gender=GENDER_MALE,
                       password=hashers.make_password('123456'),
                       character='A')
     admin.save()
     self.stdout.write(self.style.SUCCESS('添加Admin帐号成功'))
예제 #3
0
 def mutate_and_get_payload(cls, root, info, **input):
     name = input.get('name')
     auth = input.get('auth_provider').get('email')
     email = auth.get('email')
     password = auth.get('password')
     if UserModel.objects.filter(email=email).exists():
         raise Exception('A user with that email address already exists!')
     user = UserModel(
         name=name,
         email=email,
         password=password,
     )
     user.save()
     return CreateUser(user=user)
예제 #4
0
def create_session():
    token = parse_request_parameter(request, 'token')

    # check valid token
    req = transport_requests.Request()
    claims = google.oauth2.id_token.verify_firebase_token(token, req)
    if not claims:
        return 'Unauthorized', 401

    # check authorized users
    email = claims["email"]
    authorized_users = get_config("authorized_users")
    ok = False
    for au in authorized_users:
        ok = ok or (au["email"] == email)

    if not ok:
        return 'Unauthorized', 401

    # create user if not exist
    user_id = email
    um = UserModel.get(user_id)
    if um is None:
        name = email
        if "name" in claims:
            name = claims["name"]

        screen_name = re.sub(r"@.*", "", email)

        um = UserModel.from_dict({
            "user_id": user_id,
            "name": name,
            "email": email,
            "screen_name": screen_name,
        })
        um.put()

    # create session
    session_id = get_random_str("session_")
    sm = SessionModel.from_dict({
        "session_id": session_id,
        "user_id": user_id,
        "screen_name": um.screen_name,
        "created_at": utcnow()
    })
    sm.put()
    # todo: session cache

    return jsonify({"session": session_id})
예제 #5
0
    def delete(self, username):
        """
        This endpoint deletes a user by its username
        ---
        tags:
          - Users
        parameters:
          - in: path
            name: username
            required: true
            description: The username of the User!
            type: string
        responses:
          responses:
            200:
              description: User deleted
            401:
              description: Authorization required
            403:
              description: Admin privilege required
        """
        # Checking claims for actually execute or not the request as expected
        claims = get_jwt_claims()
        if not claims['is_admin']:
            return {'message': 'Admin privilege required'}, 403

        user = UserModel.find_by_username(username)
        if user:
            user.delete_from_db()
        return {'message': 'User deleted'}
예제 #6
0
 def patch(cls, event: dict, context) -> dict:
     logger.info('Starting to patch a user')
     if event.get('body'):
         user_id: str = event.get('pathParameters').get('user_id')
         try:
             user: UserModel = UserModel.get(user_id)
             patch_partial_params: dict = UserSchemaPatch(
                 unknown=marshmallow.EXCLUDE).loads(event.get('body'))
             user.update(actions=[
                 getattr(UserModel, attr).set(value)
                 for attr, value in patch_partial_params.items()
             ])
             response: dict = {
                 'statusCode':
                 200,
                 'body':
                 json.dumps({
                     'message':
                     'User was patched successful',
                     'user':
                     UserSchemaGet().dump(UserModel.get(user_id))
                 })
             }
             logger.info('User was patched successful')
         except UserModel.DoesNotExist:
             response: dict = {
                 'statusCode':
                 404,
                 'body':
                 json.dumps({
                     'message': json.dumps('User does not exist'),
                 })
             }
             logger.info('User does not exist')
         except marshmallow.exceptions.ValidationError as err:
             response: dict = {
                 'statusCode': 400,
                 'body': json.dumps(err.messages)
             }
             logger.warning('Invalid data')
     else:
         response: dict = {
             'statusCode': 400,
             'body': json.dumps('Request body is empty')
         }
         logger.error('Request body is empty')
     return response
예제 #7
0
 def _get_or_404(self, username):
     store = UserModel.find_by_username(username)
     if store is None:
         abort(
             404,
             message='User with username {} not found'.format(username))
     else:
         return store
예제 #8
0
    def create_user(self, **kwargs) -> UserModel:

        with self.db_connect as db:
            user = UserModel(**kwargs)
            db.add(user)
            db.commit()
            db.refresh(user)

        return user
예제 #9
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if not data.get('phone', None) is None:
            parsed_phone = parse_phone(data['phone'])
            if parsed_phone is None:
                return {"message": "Invalid phone format for the user"}, 400

            data['phone'] = "-".join(parsed_phone).strip('-')

        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(**data)
        try:
            user.save_to_db()
        except:
            return {"message": "An error occurred creating the user."}, 500

        return {"message": "User created successfully."}, 201
예제 #10
0
def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = UserModel.login(form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=30)
    access_token = create_access_token(data={"sub": user.username},
                                       expires_delta=access_token_expires)
    return {"access_token": access_token, "token_type": "bearer"}
예제 #11
0
 def get_list(cls, event, context):
     limit = 0
     if event.get('queryStringParameters'):
         limit_str = event.get('queryStringParameters').get('limit')
         limit = int(limit_str) if limit_str else limit
     users = [item for item in UserModel.scan()]
     users_map = list(map(UserSchemaGet().dump, users))
     response = {
         'statusCode': 200,
         'body':
         json.dumps(users_map[0:limit] if limit else users_map[0:1000])
     }
     return response
def create_user(request):

    if request.method == "POST":
        body_unicode = request.body.decode("utf-8")
        print(body_unicode)
        body = json.loads(body_unicode)
        first_name = body["first_name"]
        last_name = body["last_name"]
        email = body["email"]
        phone_number = body["phone_number"]
        if body["is_manager"] == "False":
            is_manager = False
        else:
            is_manager = True
        str_password = body["password"]
        password = make_password(str_password)
        user = UserModel(
            first_name=first_name,
            last_name=last_name,
            phone_number=phone_number,
            is_manager=is_manager,
            email=email,
            password=password,
        )
        user.save()

        # users = UserModel.objects.get(phone_number =phone_number)
        # url = 'http://localhost:8000/api/token/'
        # data = {"username":phone_number,"password":str_password}
        # response = requests.post(url, data = data)
        # response_json = convert_bytes_array_to_json(response.content)
        # response_data = {"token" : response_json["token"]}
        response_data = {"status": "User Created"}
        return JsonResponse(response_data)

    else:
        response_data = {"status": "Get request not allowed."}
        return JsonResponse(response_data)
예제 #13
0
 def get(cls, event: dict, context) -> dict:
     user_id: str = event.get('pathParameters').get('user_id')
     try:
         user: UserModel = UserModel.get(user_id)
         response: dict = {
             'statusCode': 200,
             'body': json.dumps(UserSchemaGet().dump(user))
         }
     except UserModel.DoesNotExist:
         response: dict = {
             'statusCode': 404,
             'body': json.dumps({'message': 'User not found'})
         }
     return response
예제 #14
0
def signup(request):
    if request.method == "POST":
        print request.POST
        user = UserModel(username=request.POST['username'],
                         last_name=request.POST.get('last_name'),
                         first_name=request.POST.get('first_name'))
        user.set_password(request.POST['password'])
        user.save()
    return render(request, 'registration/signup.html')
예제 #15
0
def signup(request):
    if request.method == "POST":
        user = UserModel(username=request.POST['username'],
                         name=request.POST.get('username'),
                         role='instructor')
        user.set_password(request.POST['password'])
        user.save()
        return HttpResponseRedirect('/')
    return render(request, 'registration/signup.html')
예제 #16
0
    def test_if_client_is_logged_when_created(self):
        gateway = UserGateway()
        name = 'fa'
        password = '******'
        model = UserModel(1, name, password)
        gateway.create = MagicMock(return_value=model)
        c_controller = ClientController()
        c_controller.controller.users_gateway = gateway
        c_gateway = ClientGateway()
        c_controller.client_gateway = c_gateway
        c_gateway.add_to_table = MagicMock(return_value=1)
        c_gateway.login = MagicMock(return_value=1)

        self.assertTrue(c_controller.create_client(name, password))
        self.assertTrue(settings.CURRENT_USER == 1)
예제 #17
0
    def delete(self):
        """DELETE ALL OF USERS
        For testing purposes only, in production should be deactivated
        ---
        tags:
          - Users
        responses:
          200:
            description: Users deleted
        """
        # Checking claims for actually execute or not the request as expected
        claims = get_jwt_claims()

        if 'admin' not in get_current_user().roles:
            return {"message": "Forbidden: Admin privilege required"}, 403

        if not claims['is_admin']:
            return {'message': 'Forbidden: Admin privilege required'}, 403
        return UserModel.delete_all()
예제 #18
0
 def post(self):
     try:
         data = request.get_json()
         error = UserSchema().validate(data)
         if error:
             res_data = response_400(msg=str(error))
             return make_response(jsonify(res_data))
         data["password"] = UserModel.generate_password(
             password=data["password"])
         print(data)
         user = UserSchema().load(data)
         db.session.add(user)
         db.session.commit()
         user_data = UserSchema().dump(user)
         res_data = response_200({"user": user_data})
         return make_response(jsonify(res_data))
     except Exception as e:
         res_data = response_400(msg=str(e))
         return make_response(jsonify(res_data))
예제 #19
0
def register(request):
    request_form = RegisterForm(request.POST)
    if request_form.is_valid():
        post = request.POST
        user_name = post.get('user_name', '')
        pass_word1 = post.get('pass_word1', '')
        pass_word2 = post.get('pass_word2', '')
        if pass_word1 != pass_word2:
            return render(request, 'users/register.html')
        email = post.get('email', '')
        users = UserModel()
        users.username = user_name
        users.password = make_password(pass_word2)
        users.email = email
        users.save()
        return render(request, 'blog/index.html')
    else:
        return render(request, 'users/register.html')
예제 #20
0
def signup():
    if 'username' in session:
        del session["username"]
    form = SignUp()
    if form.validate_on_submit():
        already_taken = UserModel.query.filter_by(
            username=form.username.data).first()
        if already_taken != None:
            flash("Username already taken")
            return redirect("/signup")
        if form.password.data != form.password2.data:
            flash("Passwords don't match")
            return redirect("/signup")
        new_user = UserModel(username=form.username.data,
                             password=form.password.data,
                             email=form.email.data)
        db.session.add(new_user)
        db.session.commit()
        return redirect('/')
    return render_template("signup.html", form=form)
예제 #21
0
    def get(self):
        """
        Returns the list of users
        This endpoint will work for both protected and unprotected data.
        If no JWT is sent in with the request, get_jwt_identity() will return None
        For testing purposes only, in production should be deactivated
        ---
        tags:
          - Users
        responses:
          200:
            description: The list of users
            schema:
              type: object
              properties:
                users:
                  type: array
                  items:
                    $ref: '#/definitions/User'
            examples:
              { 'users': [{'id': 1, 'name': 'admin', 'username': '******'},]}
        """

        def to_json(x):
            return {
                'id': x.id,
                'username': x.username,
                'name': x.name,
                'is_admin': x.is_admin
            }

        # Access the identity of the JWT (username) with get_jwt_identity
        current_user = get_jwt_identity()
        users = list(map(lambda x: to_json(x), UserModel.find_all()))
        if current_user:
            return {'users': users}

        return {
            'users': [x['name'] for x in users],
            'message': 'More data available if logged in'
        }
예제 #22
0
 def delete(cls, event: dict, context) -> dict:
     user_id: str = event.get('pathParameters').get('user_id')
     try:
         user: UserModel = UserModel.get(user_id)
         deleted_user: dict = UserSchemaGet().dump(user)
         user.delete()
         response: dict = {
             'statusCode':
             204,
             'body':
             json.dumps({
                 'message': 'User was deleted successful',
                 'user': deleted_user
             })
         }
     except UserModel.DoesNotExist:
         response: dict = {
             'statusCode': 404,
             'body': json.dumps({'message': 'User not found'})
         }
     return response
예제 #23
0
    def post(self):
        '''
        Login and return a valid Authorization header
        '''
        args = login_parser.parse_args()

        user = UserModel.find_by_email(args['email'])

        if user and user.check_password(args['password']):
            # Generate the header
            payload = {
                'userid': user.id,
                'username': user.username,
                'email': user.email
            }
            header = generate_token_header(payload, config.PRIVATE_KEY)
            return {'Authorized': header}, http.client.OK

        return {
            "message": "Invalid email or password"
        }, http.client.UNAUTHORIZED
예제 #24
0
    def post(self):
        '''
        Create a new user
        '''
        args = user_parser.parse_args()

        if UserModel.find_by_email(args['email']):
            return {"message": "Email is already registered."}, 400

        new_user = UserModel(fname=args['fname'],
                             lname=args['lname'],
                             username=args['username'],
                             email=args['email'])

        new_user.set_password(args['password'])
        new_user.save_to_db()

        result = api_ns.marshal(new_user, user_model)

        return result, http.client.CREATED
    def test_validate_without_capital_letter_returns_false(self):
        password = '******'
        name = 'pop'

        self.assertFalse(UserModel.validate(name, password))
    def test_validate_with_correct_password(self):
        password = '******'
        name = 'pop'

        self.assertTrue(UserModel.validate(name, password))
    def test_validate_without_special_symbol_returns_false(self):
        password = '******'
        name = 'pop'

        self.assertFalse(UserModel.validate(name, password))
예제 #28
0
def register(user: UserSignUp):
    user = UserModel.register(user.username, user.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail="Incorrect username or password")
    return user
    def test_validate_with_sort_password_returns_false(self):
        password = '******'
        name = 'pop'

        self.assertFalse(UserModel.validate(name, password))
예제 #30
0
    def create(self, validated_data):
        user = UserModel(email=validated_data["email"])
        user.set_password(validated_data["password"])
        user.save()

        return user
예제 #31
0
 def make_user(self, data, **kwargs):
     uuid = data.get('id')
     if uuid and len(uuid) != 36:
         data.pop('id')
     return UserModel(**data)