Ejemplo n.º 1
0
    def validate(self):
        rv = Form.validate(self)
        if not rv:
            message = ''
            for fieldName, errorMessages in self.errors.items():
                for err in errorMessages:
                    message = message + fieldName + ': ' + err + '\n'
            flash(message, 'error')
            return False

        # Query data from database
        user = savvy_collection.find_one({EMAIL: self.email.data.rstrip()})

        if user:
            email = user.get(EMAIL, None)
            hash_password = user.get(PASSWORD, None)
            user_password = self.password.data.rstrip()
            account_token = user.get(TOKEN, '')

            if User.validate_login(hash_password, user_password):
                userObj = User(email)
                login_user(userObj)
                return True
            else:
                flash('Incorrect login credentials', 'error')
        else:
            flash('Incorrect login credentials', 'error')
        return False
Ejemplo n.º 2
0
 def authenticate(email, password):
     """
     用户登录,登录成功返回token,并且将登录时间写入数据库,登录失败返回失败原因
     :param email:
     :param password:
     :return: json
     """
     filters = {User.email == email}
     user_info = User().get_one(filters)
     user_info_password = User().get_one(filters,
                                         order='id desc',
                                         field=('password', ))
     if user_info is None:
         return BaseController().error('找不到用户')
     else:
         if User.check_password(user_info_password['password'], password):
             updated_time = int(time.time())
             User.update(email=email, updated_time=updated_time)
             token = UserAuthJWT.encode_auth_token(user_info['id'],
                                                   updated_time)
             return BaseController().successData(
                 {
                     'token': token.decode(),
                     'user': user_info
                 }, '登录成功')
         else:
             return BaseController().error('密码不正确')
Ejemplo n.º 3
0
    def validate(self):
        rv = Form.validate(self)
        if not rv:
            message = ''
            for fieldName, errorMessages in self.errors.items():
                for err in errorMessages:
                    message = message + fieldName + ': ' + err + '\n'
            flash(message, 'error')
            return False

        # Query data from database
        user = savvy_collection.find_one({ EMAIL: self.email.data.rstrip() })

        if user:
            email = user.get(EMAIL, None)
            hash_password = user.get(PASSWORD, None)
            user_password = self.password.data.rstrip()
            account_token = user.get(TOKEN, '')

            if User.validate_login(hash_password, user_password):
                userObj = User(email)
                login_user(userObj)
                return True
            else:
                flash('Incorrect login credentials', 'error')
        else:
            flash('Incorrect login credentials', 'error')
        return False
Ejemplo n.º 4
0
 def identify(self, request):
     """
     用户鉴权
     :return: list
     """
     auth_header = request.headers.get('Authorization')
     if auth_header:
         auth_tokenArr = auth_header.split(" ")
         if (not auth_tokenArr or auth_tokenArr[0] != 'JWT'
                 or len(auth_tokenArr) != 2):
             return '请传递正确的验证头信息'
         else:
             auth_token = auth_tokenArr[1]
             payload = self.decode_auth_token(auth_token)
             if not isinstance(payload, str):
                 user = User.get(payload['data']['id'])
                 if user is None:
                     return '找不到该用户信息'
                 else:
                     if user.updated_at == payload['data']['updated_at']:
                         result = payload
                     else:
                         return 'Token已更改,请重新登录获取'
             else:
                 result = payload
     else:
         return '没有提供认证token'
     return result
Ejemplo n.º 5
0
def identify(self, request):
    """
    用户鉴权
    :param request:
    :return:
    """
    auth_header = request.headers.get('Authorization')
    if auth_header:
        auth_token_list = auth_header.split(' ')
        if not auth_token_list or auth_token_list[0] != 'JWT' or len(
                auth_token_list) != 2:
            return '请传递正确的验证头信息'
        else:
            auth_token = auth_token_list[1]
            payload = self.docode_auth_token(auth_token)
            if not isinstance(payload, str):
                user = User.get(payload['data']['id'])
                if user is None:
                    return '找不到用户信息'
                else:
                    if user.updated_time == payload['data']['update_time']:
                        result = payload
                    else:
                        return 'Token已更改,请重新登录获取Token'
            else:
                result = payload
    else:
        return '没有提供认证token'
    return result
Ejemplo n.º 6
0
def posts(username):
    mongo.db.posts.remove({})
    user = User.get_from_username("critique")
    for i in range(20):
        post = Post.create_post(user, [username], "This is a Critique post!",
                                "Test post " + str(i))
        print(post.send(user, notify=False))
    return Reply().ok()
Ejemplo n.º 7
0
def search(requester):
    query = mongo.db.users.find(
        {"username": {
            "$regex": request.json["search"],
            "$options": "i"
        }})
    users = User.create_from_db_obj(query)
    overviews = [user.get_overview(requester) for user in users]

    return Reply(overviews).ok()
Ejemplo n.º 8
0
    def validate(self):
        rv = Form.validate(self)
        if not rv:
            message = ''
            for fieldName, errorMessages in self.errors.items():
                for err in errorMessages:
                    message = message + fieldName + ': ' + err + '\n'
            flash(message, 'error')
            return False

        user = savvy_collection.find_one({EMAIL: self.email.data.rstrip()})
        if user:
            flash('Email has already been taken', 'warning')
            return False
        else:
            raw_token = self.email.data + 'verification code'
            token = md5(raw_token.encode('utf-8')).hexdigest()
            user = {
                PASSWORD:
                md5(self.password.data.rstrip().encode('utf-8')).hexdigest(),
                EMAIL:
                self.email.data.rstrip(),
                CATEGORY:
                self.category.data,
                TOKEN:
                token
            }

            # insert into database
            employerId = savvy_collection.insert_one(user).inserted_id

            if self.category.data == EMPL:
                jobs_collection.insert({EMPLID: employerId})

            # url = os.getenv('SCRIPT_URI') <----------------get this to work when server is up
            # url = '127.0.0.1:5000'
            # message = """
            # Hi {},
            #
            #     You need to confirm your account by clicking this link:
            #     {}/confirmEmail/{}/{}
            #
            # Best,
            # Team SavvyHire
            # """.format(self.username.data.rstrip(),url, self.username.data.rstrip(), token)
            #
            # cmd="""echo '{}' | mail -s 'Confirm account' {}""".format(message, self.email.data.rstrip())
            # p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
            # p.communicate()

            # log in
            userObj = User(user[EMAIL])
            login_user(userObj)

            return True
Ejemplo n.º 9
0
def changepassword(email, password):
    user = savvy_collection.find_one({ EMAIL: email })
    form = changepasswordForm(request.form,user)

    if user:
        if User.validate_password(email, password):
            print (user)
            print('validated')
            print(current_user.get_id())
            return render('changepassword.html', form=form, extra=email)

    return redirect(url_for('home'))
Ejemplo n.º 10
0
def changepassword(email, password):
    user = savvy_collection.find_one({EMAIL: email})
    form = changepasswordForm(request.form, user)

    if user:
        if User.validate_password(email, password):
            print(user)
            print('validated')
            print(current_user.get_id())
            return render('changepassword.html', form=form, extra=email)

    return redirect(url_for('home'))
Ejemplo n.º 11
0
def login():

    #	print(request.)

    salt = bcrypt.gensalt()

    #print(bcrypt.hashpw(request.json['password'].encode(), salt))

    user = User.login(request.json['username'], request.json['password'])
    if user is not None:
        return Reply(user).ok()
    else:
        return Reply("Invalid username or password!").error()
Ejemplo n.º 12
0
 def authenticate(oa_account, password):
     """
     用户登录,登录成功返回token,写将登录时间写入数据库;登录失败返回失败原因
     :param oa_account:
     :param password:
     :return: json
     """
     filters = {
         User.oa_account == oa_account
     }
     userInfo = User().getOne(filters)
     userInfoPas = User().getOne(filters, order='id desc', field=('password',))
     if userInfo is None:
         return BaseController().error('找不到用户')
     else:
         if User.check_password(userInfoPas['password'], password):
             updated_at = int(time.time())
             token = UsersAuthJWT.encode_auth_token(userInfo['id'], updated_at)
             User.update(userInfo['id'], remember_token=token.decode(), last_login_time=updated_at)
             return BaseController().successData({'token': token.decode()}, '登陆成功')
         else:
             return BaseController().error('密码不正确')
Ejemplo n.º 13
0
def get_user():
    """
    获取用户信息
    :return:
    """
    result = UserAuthJWT().identify(request)
    if isinstance(result, str):
        return BaseView().error(result)
    if result['data']:
        user = User.get(result['data']['id'])
        user_dict = {
            'id': user.id,
            'name': user.name,
            'email': user.email,
            'login_time': user.updated_time,
        }
        return BaseView().success_data(user_dict)
    return BaseView().error('为找到用户')
Ejemplo n.º 14
0
def hard_reset():
    mongo.db.users.remove({})
    mongo.db.posts.remove({})
    User.create_new_user("marc",
                         "nohash",
                         validating=False,
                         following=["adam", "john"])
    User.create_new_user("adam",
                         "password",
                         validating=False,
                         patch="adam.png",
                         following=["marc", "noah"])
    User.create_new_user("john",
                         "password",
                         validating=False,
                         patch="john.png",
                         following=["adam", "critique"])
    User.create_new_user("critique",
                         "critique",
                         validating=False,
                         patch="critique.png",
                         following=["adam", "john", "marc", "noah"])
    return Reply().ok()
Ejemplo n.º 15
0
def register(params):
    """
    注册
    :param params:
    :return:
    """
    filters = {User.email == params['email']}
    user = User().get_one(filters)
    if not user:
        user = User(email=params['email'],
                    password=User.set_password(params['password']),
                    status=1)
        status = user.add(user)
        if status == True:
            return BaseView().success_data(msg='注册成功')
        return BaseView().error('注册失败')
    return BaseView().error('帐号已注册')
Ejemplo n.º 16
0
    def notify(self, users, requester):
        from app.Models.User import User

        user_keys = [
            user.get_info("notificationKey")
            for user in User.get_from_username(users)
        ]

        url = 'https://fcm.googleapis.com/fcm/send'
        key = 'AAAAxe-zm-c:APA91bFo5NK_jcUydvxbwbp1wWD3KCND2ul9xRLvZvi14aNjbAeQi6eJkbdU9wiFwawo7b6Af3rPuqoUH8q0vOfGYA40nRpIC436_SxBx2wbC1pl_CXTkA2Q_ev_yb-RUXQF66hS1YZq'
        body = {
            "registration_ids": user_keys,
            "priority": "high",
            "data": {
                "title": "Critique",
                "body": "from " + requester.username,
            }
        }
        headers = {
            "Content-Type": "application/json",
            "Authorization": "key=" + key
        }
        r = requests.post(url, data=json.dumps(body), headers=headers)
        return Reply(str(r.reason)).ok()
Ejemplo n.º 17
0
def get_patch(username):
    user = User.get_from_username(username)
    print(user)
    path = user.get_patch_path()
    return send_file(path, mimetype='image/png')
Ejemplo n.º 18
0
def activate(username, token):
    if User.validate_rego_token(username, token):
        login_user(User(username))
        return redirect(url_for("account"))
    return redirect(url_for("home"))
Ejemplo n.º 19
0
def activate(username, token):
    if User.validate_rego_token(username, token):
        login_user(User(username))
        return redirect(url_for('account'))
    return redirect(url_for('home'))