Exemplo n.º 1
0
def user_change_password():
    user = session.get('user_info')
    o_password = request.values.get('old_password')
    n_password = request.values.get('new_password')
    n2_password = request.values.get('new2_password')
    session['action'] = 'password'

    if n_password != n2_password:
        session['error_message'] = '新密码输入不一致.'
        return redirect(url_for('user_profile'))

    if len(n_password) < 8:
        session['error_message'] = '密码必须8位及以上.'
        return redirect(url_for('user_profile'))

    user_key = '%s:%s' % ('user', user.get('username'))
    user_info = json.loads(r_session.get(user_key).decode('utf-8'))

    hashed_password = hash_password(o_password)

    if user_info.get('password') != hashed_password:
        session['error_message'] = '原密码错误'
        return redirect(url_for('user_profile'))

    user_info['password'] = hash_password(n_password)
    r_session.set(user_key, json.dumps(user_info))

    return redirect(url_for('user_profile'))
Exemplo n.º 2
0
def user_change_password():
    user = session.get("user_info")
    o_password = request.values.get("old_password")
    n_password = request.values.get("new_password")
    n2_password = request.values.get("new2_password")
    session["action"] = "password"

    if n_password != n2_password:
        session["error_message"] = "新密码输入不一致."
        return redirect(url_for("user_profile"))

    if len(n_password) < 8:
        session["error_message"] = "密码必须8位及以上."
        return redirect(url_for("user_profile"))

    user_key = "%s:%s" % ("user", user.get("username"))
    user_info = json.loads(r_session.get(user_key).decode("utf-8"))

    hashed_password = hash_password(o_password)

    if user_info.get("password") != hashed_password:
        session["error_message"] = "原密码错误"
        return redirect(url_for("user_profile"))

    user_info["password"] = hash_password(n_password)
    r_session.set(user_key, json.dumps(user_info))

    return redirect(url_for("user_profile"))
Exemplo n.º 3
0
def user_login():
    username = request.values.get('username')
    password = request.values.get('password')

    hashed_password = hash_password(password)

    user_info = r_session.get('%s:%s' % ('user', username))
    if user_info is None:
        session['error_message'] = '用户不存在'
        return redirect(url_for('login'))

    user = json.loads(user_info.decode('utf-8'))

    if user.get('password') != hashed_password:
        session['error_message'] = '密码错误'
        return redirect(url_for('login'))

    if not user.get('active'):
        session['error_message'] = '您的账号已被禁用.'
        return redirect(url_for('login'))

    if user.get('log_as_body') is not None:
        if len(user.get('log_as_body')) > 0:
            r_session.set('%s:%s' % ('record', username), json.dumps(dict(diary=user.get('log_as_body')))) # 创建新通道,转移原本日记
            user['log_as_body'] = []

    user['login_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 记录登陆时间
    r_session.set('%s:%s' % ('user', username), json.dumps(user)) # 修正数据

    if r_session.get('%s:%s' % ('record', username)) is None:
        r_session.set('%s:%s' % ('record', username), json.dumps(dict(diary=[]))) # 创建缺失的日记

    session['user_info'] = user

    return redirect(url_for('dashboard'))
Exemplo n.º 4
0
def update_profile(request):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        result = {'status': 'error',
                  'error': 'Not authenticated.'
                  }
        return util.json_response(result)

    if request.POST.get('apisecret') != g.user["apisecret"]:
        result = {'status': 'error',
                  'error': 'Wrong form secret'
                  }
        return util.json_response(result)


    password = request.POST.get('password')    #optinal
    email = request.POST.get('email')
    about = request.POST.get('about')

    email, msg = util.check_string(email, maxlen=128)
    if email is None:
        result = {
            'status': 'error',
            'error': 'email ' + msg
            }
        return util.json_response(result)

    about, msg = util.check_string(about, maxlen=256)
    if about is None:
        result = {
            'status': 'error',
            'error': 'about ' + msg
            }
        return util.json_response(result)

    r = g.redis

    if password:
        password, msg = util.check_string(password, config.PasswordMinLength)
        if not password:
            result = {
                'status': 'error',
                'error': 'password ' + msg
                }
            return util.json_response(result)

        r.hset("user:"******"password",
               util.hash_password(password, g.user['salt']))

    r.hmset("user:"******"about": about.rstrip(),
            "email": email
            })
    return util.json_response({'status': "ok"})
Exemplo n.º 5
0
def create_user(form):
    """
    Create a new user given registration form
    """
    hashed, salt = hash_password(form["password"])
    new_user = User(email=form["email"], hashed_password=hashed, salt=salt)
    # give user access to public data
    authorize_public_data(new_user)
    db.session.add(new_user)
    db.session.commit()
    return new_user
Exemplo n.º 6
0
def admin_change_password(username):
    n_password = request.values.get('new_password')

    if len(n_password) < 8:
        session['error_message'] = '密码必须8位以上.'
        return redirect(url_for(endpoint='admin_user_management', username=username))

    user_key = '%s:%s' % ('user', username)
    user_info = json.loads(r_session.get(user_key).decode('utf-8'))

    user_info['password'] = hash_password(n_password)
    r_session.set(user_key, json.dumps(user_info))

    return redirect(url_for(endpoint='admin_user_management', username=username))
Exemplo n.º 7
0
def registration():
    if request.method == 'POST':
        req = request.form
        hashed_password = util.hash_password(req['password'])
        if data_manager.check_user_data('username', req['username']) is True:
            flash('This username is already taken!')
            return redirect(request.url)
        elif data_manager.check_user_data('email_address', req['email']) is True:
            flash('This email address is already taken!')
            return redirect(request.url)
        elif len(req['password']) < 7:
            flash('Too short password! (Min. 7 character.)')
            return redirect(request.url)
        elif not util.verify_password(req['password_again'], hashed_password):
            flash('The passwords are different!')
            return redirect(request.url)
        else:
            list_of_data = [req['username'], req['email'], util.hash_password(req['password'])]
            data_manager.add_new_user(list_of_data)
            session['id'] = data_manager.get_user_id(req['username'])[0]['id']
            session['username'] = req['username']
            return redirect(url_for('route_main'))
    return render_template('registration.html')
Exemplo n.º 8
0
def admin_change_password(username):
    n_password = request.values.get('new_password')

    if len(n_password) < 8:
        session['error_message'] = '密码必须8位以上.'
        return redirect(url_for(endpoint='admin_user_management', username=username))

    user_key = '%s:%s' % ('user', username)
    user_info = json.loads(r_session.get(user_key).decode('utf-8'))

    user_info['password'] = hash_password(n_password)
    r_session.set(user_key, json.dumps(user_info))

    return redirect(url_for(endpoint='admin_user_management', username=username))
Exemplo n.º 9
0
def create_user_account():
    api_key = util.random_api_key()
    data = request.get_json()
    user = User()
    user.username = data['username']
    password = data['password']
    hashed_pass = util.hash_password(password)
    user.password_hash = hashed_pass
    user.first_name = data['first_name']
    user.last_name = data['last_name']
    user.email = data['email']
    user.api_key = api_key
    user.save()
    return jsonify({"api_key": account.api_key})
Exemplo n.º 10
0
def add_new_user(cursor, new_name, new_password):
    submission_time = util.get_submission_time()
    new_password = util.hash_password(new_password)
    try:
        cursor.execute(
            """
        insert into regduser(id, hashed_password, submission_time)
        values (%(id)s, %(hashed_password)s, %(submission_time)s);
        """, {
                'id': new_name,
                'hashed_password': new_password,
                'submission_time': submission_time
            })
    except:
        return 1
Exemplo n.º 11
0
def create_provider_account():
    api_key = util.random_api_key()
    data = request.get_json()
    provider = Provider()
    provider.username = data['username']
    password = data['password']
    hashed_pass = util.hash_password(password)
    provider.password_hash = hashed_pass
    provider.api_key = api_key
    provider.hospital = data['hospital']
    provider.department = data['department']
    provider.doctor_name = data['doctor_name']
    provider.email = data['email']
    provider.save()
    return jsonify({"api_key": account.api_key})
Exemplo n.º 12
0
def registration():
    username = None
    password = None
    if request.method == "POST":
        username = request.form.get('username').lower()
        password = util.hash_password(request.form.get('password'))
        if data_manager.check_user_exists(username):
            flash(
                'The user already exists. Please choose a different username')
            redirect(url_for('registration'))
        else:
            data_manager.add_new_user(username, password)
            flash('Succesulf registration. Login to continue.')
            return redirect(url_for('login'))
    return render_template('registration.html')
Exemplo n.º 13
0
def user_register():
    invitation_code = request.values.get('invitation_code')

    if not r_session.sismember('invitation_codes', invitation_code) and \
    not r_session.sismember('public_invitation_codes', invitation_code):
        session['error_message'] = '无效的邀请码。'
        return redirect(url_for('register'))

    username = request.values.get('username')
    password = request.values.get('password')
    re_password = request.values.get('re_password')

    if username == '':
        session['error_message'] = '用户名不能为空.'
        return redirect(url_for('register'))

    if r_session.get('%s:%s' % ('user', username)) is not None:
        session['error_message'] = '该用户名已存在.'
        return redirect(url_for('register'))

    r = r"(^[a-zA-Z]+[a-zA-Z0-9_-]+$)"
    if re.match(r, username) is None:
        session['error_message'] = '用户名由字母开头数字和下划线组成.'
        return redirect(url_for('register'))

    if len(username) < 6 or len(username) > 20:
        session['error_message'] = '用户名长度在6~20个字符之间.'
        return redirect(url_for('register'))

    if password != re_password:
        session['error_message'] = '两次输入的密码不一致.'
        return redirect(url_for('register'))

    if len(password) < 8:
        session['error_message'] = '输入的密码必须8位数以上.'
        return redirect(url_for('register'))

    r_session.srem('invitation_codes', invitation_code)
    r_session.srem('public_invitation_codes', invitation_code)

    user = dict(username=username, password=hash_password(password), id=str(uuid.uuid1()),
                active=True, is_admin=False, max_account_no=20,
                created_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    r_session.set('%s:%s' % ('user', username), json.dumps(user))
    r_session.sadd('users', username)

    session['info_message'] = '恭喜你,注册成功.'
    return redirect(url_for('register'))
Exemplo n.º 14
0
def user_register():
    invitation_code = request.values.get('invitation_code')

    if not r_session.sismember('invitation_codes', invitation_code) and \
    not r_session.sismember('public_invitation_codes', invitation_code):
        session['error_message'] = '无效的邀请码。'
        return redirect(url_for('register'))

    username = request.values.get('username')
    password = request.values.get('password')
    re_password = request.values.get('re_password')

    if username == '':
        session['error_message'] = '用户名不能为空.'
        return redirect(url_for('register'))

    if r_session.get('%s:%s' % ('user', username)) is not None:
        session['error_message'] = '该用户名已存在.'
        return redirect(url_for('register'))

    r = r"^[a-zA-Z0-9_.+-]+$"
    if re.match(r, username) is None:
        session['error_message'] = '用户名含有非法字符.'
        return redirect(url_for('register'))

    if len(username) < 6 or len(username) > 20:
        session['error_message'] = '用户名长度6~20个字符.'
        return redirect(url_for('register'))

    if password != re_password:
        session['error_message'] = '两次输入的密码不一致.'
        return redirect(url_for('register'))

    if len(password) < 8:
        session['error_message'] = '输入的密码必须8位数以上.'
        return redirect(url_for('register'))

    r_session.srem('invitation_codes', invitation_code)
    r_session.srem('public_invitation_codes', invitation_code)

    user = dict(username=username, password=hash_password(password), id=str(uuid.uuid1()),
                active=True, is_admin=False, max_account_no=20,
                created_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    r_session.set('%s:%s' % ('user', username), json.dumps(user))
    r_session.sadd('users', username)

    session['info_message'] = '恭喜你,注册成功.'
    return redirect(url_for('register'))
Exemplo n.º 15
0
    def set_password(self, new_password):
        """May raise util.BadPassword."""
        logging.info("Setting new password {} for user {}.".format(
            new_password, self))

        self.hashed_password = util.hash_password(new_password)

        # Alert the user that their password has been changed.
        mandrill.send(
            to_address=self.email,
            subject="Your Mindset Kit password has been changed.",
            template="change_password.html",
        )

        logging.info('User.set_password queueing an email to: {}'.format(
            self.email))
Exemplo n.º 16
0
def registration():
    if request.method == 'POST':
        user = {
            'id': util.key_generator(),
            'registration_time': util.get_current_datetime(),
            'username': request.form.get('username'),
            'email': request.form.get('email'),
            'password': util.hash_password(request.form.get('password')),
            'role': 'user'
        }
        data_handler.add_new_user(user)
        return redirect(url_for('route_list'))

    return render_template('registration.html',
                           page_title='Registration',
                           button_title='Registrate')
Exemplo n.º 17
0
def registration():
    if request.method == 'POST':
        users = data_handler.get_usernames()
        for user in users:
            if user['username'] == request.form['username']:
                error = 'Username already exists, please choose another one!'
                return render_template('registration.html', error=error)
        if request.form['username'] and request.form['password']:
            password = util.hash_password(request.form['password'])
            user = {'username': request.form['username'], 'password': password}
            data_handler.add_new_user(user)
            flash('Successful registration. Log in to continue.')
            return redirect('/login')
        else:
            error = 'Please, fill in both fields.'
            return render_template('registration.html', error=error)
    return render_template('registration.html')
Exemplo n.º 18
0
def registration():
    if request.method == "GET":
        try:
            error = False
            return render_template('registration.html', error=error)
        except (IndexError, UndefinedError):
            abort(404)
    elif request.method == "POST":
        username = request.form['username']
        registration_date = datetime.now().isoformat(timespec='seconds')
        password = hash_password(request.form['password'])
        try:
            data_manager.registration(username, password, registration_date)
            return redirect('/')
        except IntegrityError:
            error = True
            return render_template('registration.html', error=error)
Exemplo n.º 19
0
def install():
    import random, uuid
    from util import hash_password

    if r_session.scard('users') == 0:
        _chars = "0123456789ABCDEF"
        username = ''.join(random.sample(_chars, 6))
        password = ''.join(random.sample(_chars, 6))

        user = dict(username=username, password=hash_password(password), id=str(uuid.uuid1()),
                    active=True, is_admin=True, max_account_no=5,
                    created_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        r_session.set('%s:%s' % ('user', username), json.dumps(user))
        r_session.sadd('users', username)
        return 'username:%s,password:%s' % (username, password)

    return redirect(url_for('login'))
Exemplo n.º 20
0
def install():
    import random, uuid
    from util import hash_password

    if r_session.scard('users') == 0:
        _chars = "0123456789ABCDEF"
        username = ''.join(random.sample(_chars, 6))
        password = ''.join(random.sample(_chars, 6))

        user = dict(username=username, password=hash_password(password), id=str(uuid.uuid1()),
                    active=True, is_admin=True, max_account_no=2,
                    created_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        r_session.set('%s:%s' % ('user', username), json.dumps(user))
        r_session.sadd('users', username)
        return 'username:%s,password:%s' % (username, password)

    return redirect(url_for('login'))
Exemplo n.º 21
0
def registration():
    if request.method == 'GET':
        return render_template('register.html')
    if request.form.get('password') != request.form.get('confirm-password'):
        return render_template(
            'register.html',
            error="Password and Confirm password doesn't match!")
    password = util.hash_password(request.form.get('password'))
    username = request.form.get('username')
    if data_manager.get_user(username):
        return render_template('register.html',
                               error='This username already exists!')
    user = data_manager.create_user(username, password)
    if user is False:
        return render_template('register.html',
                               error='This username already exists!')
    return redirect(url_for('login'))
Exemplo n.º 22
0
def registration():
    if request.method == 'POST':
        hashed_pw = util.hash_password(request.form['password'])
        user_name = request.form['username']
        error = data_manager.save_user(user_name, hashed_pw)
        if error:
            return render_template('reg_login.html',
                                   error=error,
                                   title='Registration',
                                   server_function='registration',
                                   submit_text='Register!')
        else:
            return redirect('/')
    return render_template('reg_login.html',
                           title='Registration',
                           server_function='registration',
                           submit_text='Register!')
Exemplo n.º 23
0
def user_register():
    email = request.values.get('username')
    invitation_code = request.values.get('invitation_code')
    username = request.values.get('username')
    password = request.values.get('password')
    re_password = request.values.get('re_password')

    if not r_session.sismember('invitation_codes', invitation_code) and \
            not r_session.sismember('public_invitation_codes', invitation_code):
        session['error_message'] = '无效的邀请码。'
        return redirect(url_for('register'))

    if username == '':
        session['error_message'] = '账号名不能为空。'
        return redirect(url_for('register'))

    if r_session.get('%s:%s' % ('user', username)) is not None:
        session['error_message'] = '该账号名已存在。'
        return redirect(url_for('register'))

    if password != re_password:
        session['error_message'] = '新密码输入不一致.'
        return redirect(url_for('register'))

    if len(password) < 8:
        session['error_message'] = '密码必须8位及以上.'
        return redirect(url_for('register'))

    r_session.srem('invitation_codes', invitation_code)
    r_session.srem('public_invitation_codes', invitation_code)

    user = dict(username=username,
                password=hash_password(password),
                id=str(uuid.uuid1()),
                active=True,
                is_admin=False,
                max_account_no=20,
                email=email,
                created_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    r_session.set('%s:%s' % ('user', username), json.dumps(user))
    r_session.set('%s:%s' % ('record', username), json.dumps(dict(diary=[])))
    r_session.sadd('users', username)

    session['info_message'] = '恭喜你,注册成功.'
    return redirect(url_for('register'))
Exemplo n.º 24
0
def login():
    if request.method == "POST":
        email = request.form["email"]
        password = request.form["password"]
        if data_manager.get_usernames(email) is False:
            psw = util.hash_password(password)
            reg_password = data_manager.get_password(email)
            is_matching = util.verify_password(password, reg_password)
            if is_matching:
                session['email'] = request.form['email']
                return redirect(url_for('main_page'))
            else:
                message = "Wrong e-mail or password!"
                return render_template('login_fail.html', message=message)
        else:
            message = "Wrong e-mail or password!"
            return render_template('login_fail.html', message=message)
    return render_template('login.html')
Exemplo n.º 25
0
 def create(self):
     self.created_at = time.time()
     if not self.validate():
         return
     if User.find_first('where email = ?', self.email):
         self.errors = {'email': u'此email已被占用'}
         return
     if User.find_first('where name = ?', self.name):
         self.errors = {'name': u'此用戶名已被注冊'}
         return
     if not self.password_confirm:
         self.errors = {'password_confirm': u'确认密码不能为空'}
         return
     if self.password != self.password_confirm:
         self.errors = {'password': u'兩次密碼輸入不一致'}
         return
     self.password = hash_password(self.password)
     self.insert()
     return self.id
Exemplo n.º 26
0
def user_register():
    invitation_code = request.values.get("invitation_code")
    username = request.values.get("username")
    password = request.values.get("password")
    re_password = request.values.get("re_password")

    if not r_session.sismember("invitation_codes", invitation_code) and not r_session.sismember(
        "public_invitation_codes", invitation_code
    ):
        session["error_message"] = "无效的邀请码。"
        return redirect(url_for("register"))

    if username == "":
        session["error_message"] = "账号名不能为空。"
        return redirect(url_for("register"))

    if r_session.get("%s:%s" % ("user", username)) is not None:
        session["error_message"] = "该账号名已存在。"
        return redirect(url_for("register"))

    if password != re_password:
        session["error_message"] = "新密码输入不一致."
        return redirect(url_for("register"))

    if len(password) < 8:
        session["error_message"] = "密码必须8位及以上."
        return redirect(url_for("register"))

    r_session.srem("invitation_codes", invitation_code)
    r_session.srem("public_invitation_codes", invitation_code)

    user = dict(
        username=username,
        password=hash_password(password),
        id=str(uuid.uuid1()),
        active=True,
        is_admin=False,
        max_account_no=2,
        created_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    )
    r_session.set("%s:%s" % ("user", username), json.dumps(user))
    r_session.sadd("users", username)
    return redirect(url_for("login"))
Exemplo n.º 27
0
    def change_password(self, origin_password, password, password_confirm):
        if not origin_password:
            self.errors['origin_password'] = u'当前密码不能为空'

        if not password:
            self.errors['password'] = u'密码不能为空'

        if not password_confirm:
            self.errors['password_confirm'] = u'确认密码不能为空'

        if password!= password_confirm:
            self.errors['password_confirm'] = u'两次密码不一致'

        if self.errors:
            return False

        self.password = hash_password(self.password)

        self.update()
Exemplo n.º 28
0
 def create(self):
     self.created_at = time.time()
     if not self.validate():
         return
     if User.find_first('where email = ?', self.email):
         self.errors = {'email': u'此email已被占用'}
         return
     if User.find_first('where name = ?', self.name):
         self.errors = {'name': u'此用戶名已被注冊'}
         return
     if not self.password_confirm:
         self.errors = {'password_confirm': u'确认密码不能为空'}
         return
     if self.password != self.password_confirm:
         self.errors = {'password': u'兩次密碼輸入不一致'}
         return
     self.password = hash_password(self.password)
     self.insert()
     return self.id
Exemplo n.º 29
0
    def change_password(self, origin_password, password, password_confirm):
        if not origin_password:
            self.errors['origin_password'] = u'当前密码不能为空'

        if not password:
            self.errors['password'] = u'密码不能为空'

        if not password_confirm:
            self.errors['password_confirm'] = u'确认密码不能为空'

        if password != password_confirm:
            self.errors['password_confirm'] = u'两次密码不一致'

        if self.errors:
            return False

        self.password = hash_password(self.password)

        self.update()
Exemplo n.º 30
0
def save_user():
    sent_data = request.form

    new_data = {
        'user_name': sent_data['user_name'],
        'password': util.hash_password(sent_data['password']),
    }
    insert_data = data_handler.add_new_user(
        new_data['user_name'],
        new_data['password']
    )

    registration_time = 0
    error_handler = 1
    print(insert_data[registration_time])
    if insert_data[error_handler] == -1:
        return render_template('registration.html', error=True)

    return redirect('/')
Exemplo n.º 31
0
def register():
    if request.method == "GET":
        return render_template('register.html')
    if request.method == "POST":
        username = request.form['usernameRegister']
        password = request.form['passwordRegister']
        password_confirm = request.form['passwordConfirm']
        email = request.form['email']

        if data_manager.username_exist(username):
            return render_template('register.html',
                                   message='Username already exist')
        if password != password_confirm:
            return render_template('register.html',
                                   message='Two passwords don\'t match')
        else:
            hash_password = util.hash_password(password)
            data_manager.register_user(username, email, hash_password)
            return redirect('/login')
Exemplo n.º 32
0
def create_account():
    data = request.get_json()
    username = data.get("username")
    password = data.get("password")
    password = bytes(password, "utf-8")
    hashed_password = hash_password(password)
    with connect(DBPATH) as connection:
        cursor = connection.cursor()
        SQL = """INSERT INTO np_accounts (
        username, password_hash) VALUES (?, ?);"""
        values = (username, hashed_password)
        cursor.execute(SQL, values)

        SQL = """SELECT pk FROM np_accounts
        WHERE username=? AND password_hash=?;"""

        np_pk = cursor.execute(SQL, values).fetchone()[0]
        return jsonify({"pk": np_pk})
    return jsonify({"SQL": "ERROR"})
Exemplo n.º 33
0
def register_user():
    email = request.values.get('username')
    username = request.values.get('username')
    password = request.values.get('password')
    re_password = request.values.get('re_password')
    r = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
    if re.match(r, email) is None:
        session['error_message'] = '邮箱地址格式不正确.'
        return redirect(url_for('add_user'))
    if username == '':
        session['error_message'] = '账号名不能为空。'
        return redirect(url_for('add_user'))
    if r_session.get('%s:%s' % ('user', username)) is not None:
        session['error_message'] = '该账号名已存在。'
        return redirect(url_for('add_user'))
    if password != re_password:
        session['error_message'] = '密码输入不一致.'
        return redirect(url_for('add_user'))
    if len(password) < 8:
        session['error_message'] = '密码必须8位及以上.'
        return redirect(url_for('add_user'))
    if r_session.sismember('email', email):
        session['error_message'] = '该邮件地址已被注册.'
        return redirect(url_for('add_user'))
    config_key = '%s:%s' % ('user', 'system')
    config_info = json.loads(r_session.get(config_key).decode('utf-8'))
    if 'trial_period' not in config_info.keys():
        config_info['trial_period'] = 14
    user = dict(username=username, password=hash_password(password), id=str(uuid.uuid1()),
                active=True, is_admin=False, max_account_no=1, email=email,total_account_point=config_info['trial_period'],
                created_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    days=int(user.get('total_account_point')/user.get('max_account_no'))
    if days<36500:
        user['expire_date'] = (datetime.now() + timedelta(days=days)).strftime('%Y-%m-%d')
    else:
        user['expire_date'] = (datetime.now() + timedelta(days=36500)).strftime('%Y-%m-%d')
    r_session.set('%s:%s' % ('user', user.get('username')), json.dumps(user))
    r_session.set('%s:%s' % ('record', user.get('username')), json.dumps(dict(diary=[])))
    r_session.sadd('users', user.get('username'))
    r_session.sadd('email', user.get('email'))
    session['info_message'] = '注册成功'
    return redirect(url_for('admin_user'))
Exemplo n.º 34
0
def create_provider_account():
    api_key = util.random_api_key()
    unic_id = util.random_unic_id()
    data = request.get_json()
    provider = Provider()
    provider.username = data['username']
    password = data['password']
    hashed_pass = util.hash_password(password)
    provider.password_hash = hashed_pass
    provider.api_key = api_key
    provider.hospital = data['hospital']
    provider.department = data['department']
    provider.doctor_name = data['doctor_name']
    provider.email = data['email']
    provider.unic_id = unic_id
    pub, pri = rsa.newkeys(512)
    provider.pub_key = pub.save_pkcs1(format="PEM")
    provider.pri_key = pri.save_pkcs1(format="PEM")
    provider.save()
    return jsonify({"api_key": provider.api_key})
Exemplo n.º 35
0
def user_login():
    username = request.values.get('username')
    password = request.values.get('password')

    hashed_password = hash_password(password)

    user_info = r_session.get('%s:%s' % ('user', username))
    if user_info is None:
        session['error_message'] = '用户不存在'
        return redirect(url_for('login'))

    user = json.loads(user_info.decode('utf-8'))

    if user.get('password') != hashed_password:
        session['error_message'] = '密码错误'
        return redirect(url_for('login'))

    if not user.get('active'):
        session['error_message'] = '您的账号已被禁用.'
        return redirect(url_for('login'))

    if user.get('log_as_body') is not None:
        if len(user.get('log_as_body')) > 0:
            r_session.set('%s:%s' % ('record', username),
                          json.dumps(dict(
                              diary=user.get('log_as_body'))))  # 创建新通道,转移原本日记
            user['log_as_body'] = []

    user['login_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 记录登陆时间
    r_session.set('%s:%s' % ('user', username), json.dumps(user))  # 修正数据

    if r_session.get('%s:%s' % ('record', username)) is None:
        r_session.set('%s:%s' % ('record', username),
                      json.dumps(dict(diary=[])))  # 创建缺失的日记

    session['user_info'] = user

    guest_diary(request, username)

    return redirect(url_for('dashboard'))
Exemplo n.º 36
0
def update_profile(request):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        result = {'status': 'error', 'error': 'Not authenticated.'}
        return util.json_response(result)

    if request.POST.get('apisecret') != g.user["apisecret"]:
        result = {'status': 'error', 'error': 'Wrong form secret'}
        return util.json_response(result)

    password = request.POST.get('password')  #optinal
    email = request.POST.get('email')
    about = request.POST.get('about')

    email, msg = util.check_string(email, maxlen=128)
    if email is None:
        result = {'status': 'error', 'error': 'email ' + msg}
        return util.json_response(result)

    about, msg = util.check_string(about, maxlen=256)
    if about is None:
        result = {'status': 'error', 'error': 'about ' + msg}
        return util.json_response(result)

    r = g.redis

    if password:
        password, msg = util.check_string(password, config.PasswordMinLength)
        if not password:
            result = {'status': 'error', 'error': 'password ' + msg}
            return util.json_response(result)

        salt = g.user.get('salt', util.get_rand())
        r.hmset("user:"******"password": util.hash_password(password, salt),
            "salt": salt
        })

    r.hmset("user:"******"about": about.rstrip(), "email": email})
    return util.json_response({'status': "ok"})
Exemplo n.º 37
0
    def do(self):
        new_password = self.request.get('new_password') or None
        auth_response = self.authenticate(
            auth_type='direct',
            username=self.request.get('username'),
            password=self.request.get('current_password'))
        if auth_response is False or auth_response is None:
            return {'success': True, 'data': 'invalid_credentials'}
        user = auth_response
        user.hashed_password = util.hash_password(new_password)
        user.put()

        # Alert the user that their password has been changed.
        mandrill.send(to_address=user.login_email,
                      subject=config.change_password_subject,
                      body=mandrill.render_markdown(
                          config.change_password_body))

        logging.info('api_handlers.ChangePasswordHandler')
        logging.info('sending an email to: {}'.format(user.login_email))

        return {'success': True, 'data': 'changed'}
Exemplo n.º 38
0
def user_login():
    try:
        username = request.values.get('username')
        password = request.values.get('password')
        hashed_password = hash_password(password)
        user_info = r_session.get('%s:%s' % ('user', username))
        if user_info is None:
            session['error_message'] = '用户不存在'
            return redirect(url_for('login'))

        user = json.loads(user_info.decode('utf-8'))
        if user.get('password') != hashed_password:
            session['error_message'] = '密码错误'
            return redirect(url_for('login'))
        if not user.get('active'):
            session['error_message'] = '您的账号已被禁用.'
            return redirect(url_for('login'))
        session['user_info'] = user

        return redirect(url_for('dashboard'))
    except Exception as e:
        return  
Exemplo n.º 39
0
def create_user(name,
                birth_date,
                avatar_path,
                password,
                desc=None,
                user_tags=""):
    """
    Create a user
    :param user_tags:
    :param avatar_path:
    :param name:
    :param birth_date:
    :param password:
    :return: username:
    """
    cursor = db.cursor()

    username = util.gen_username(name)
    reward_profile = create_reward_profile()

    create_sql = "INSERT INTO user (username,name,avatar_path,birth_date,password,reward_profile_id,user_tags,description) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)"
    values = (
        username,
        name,
        avatar_path,
        birth_date,
        util.hash_password(password),
        reward_profile,
        user_tags.replace(" ", ""),  # remove white space in tags
        desc)

    try:
        cursor.execute(create_sql, values)
        db.commit()
    except:
        print("Unable to create user")
        raise Exception

    return username
Exemplo n.º 40
0
def user_register():
    invitation_code = request.values.get('invitation_code')
    username = request.values.get('username')
    password = request.values.get('password')
    re_password = request.values.get('re_password')

    if not r_session.sismember('invitation_codes', invitation_code) and \
            not r_session.sismember('public_invitation_codes', invitation_code):
        session['error_message'] = '无效的邀请码。'
        return redirect(url_for('register'))

    if username == '':
        session['error_message'] = '账号名不能为空。'
        return redirect(url_for('register'))

    if r_session.get('%s:%s' % ('user', username)) is not None:
        session['error_message'] = '该账号名已存在。'
        return redirect(url_for('register'))

    if password != re_password:
        session['error_message'] = '新密码输入不一致.'
        return redirect(url_for('register'))

    if len(password) < 8:
        session['error_message'] = '密码必须8位及以上.'
        return redirect(url_for('register'))

    r_session.srem('invitation_codes', invitation_code)
    r_session.srem('public_invitation_codes', invitation_code)

    user = dict(username=username, password=hash_password(password), id=str(uuid.uuid1()),
                active=True, is_admin=False, max_account_no=20,
                created_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    r_session.set('%s:%s' % ('user', username), json.dumps(user))
    r_session.set('%s:%s' % ('record', username), json.dumps(dict(diary=[])))
    r_session.sadd('users', username)

    session['info_message'] = '恭喜你,注册成功.'
    return redirect(url_for('register'))
Exemplo n.º 41
0
def create_user(username, password, userip):
    r = g.redis
    username = username.lower()
    if r.exists("username.to.id:" + username):
        return None, "Username exists, please try a different one."

    if not util.lock('create_user.' + username):
        return None, "Please wait some time before creating a new user."

    user_id = r.incr("users.count")
    auth_token = util.get_rand()
    salt = util.get_rand()
    now = int(time.time())

    pl = r.pipeline()
    pl.hmset("user:%s" % user_id, {
            "id": user_id,
            "username": username,
            "salt": salt,
            "password": util.hash_password(password, salt),
            "ctime": now,
            "karma": config.UserInitialKarma,
            "about": "",
            "email": "",
            "auth": auth_token,
            "apisecret": util.get_rand(),
            "flags": "",
            "karma_incr_time": now,
            "replies": 0,
            })

    pl.set("username.to.id:" + username, user_id)
    pl.set("auth:" + auth_token, user_id)
    pl.execute()

    util.unlock('create_user.' + username)

    return auth_token, None
Exemplo n.º 42
0
def shipper_account():
    data = request.get_json()
    company_name = data.get("company")
    username = data.get("username")
    password = data.get("password")
    email = data.get("email")
    password = bytes(password, "utf-8")
    hashed_password = hash_password(password)
    with connect(DBPATH) as connection:
        cursor = connection.cursor()

        SQL = """INSERT INTO shipper_accounts (company_name,
        username, email, password_hash) VALUES (?, ?, ?, ?);"""
        values = (company_name, username, email, hashed_password)
        cursor.execute(SQL, values)

        SQL = """SELECT pk FROM shipper_accounts
        WHERE username=? AND password_hash=?;"""
        values = (username, hashed_password)
        shipper_pk = cursor.execute(SQL, (values)).fetchone()[0]

        return jsonify({"pk": shipper_pk})
    return jsonify({"SQL": "ERROR"})
Exemplo n.º 43
0
def update_profile(request):
    auth_user(request.cookies.get("auth"))
    if not g.user:
        result = {"status": "error", "error": "Not authenticated."}
        return util.json_response(result)

    if request.POST.get("apisecret") != g.user["apisecret"]:
        result = {"status": "error", "error": "Wrong form secret"}
        return util.json_response(result)

    password = request.POST.get("password")  # optinal
    email = request.POST.get("email")
    about = request.POST.get("about")

    email, msg = util.check_string(email, maxlen=128)
    if email is None:
        result = {"status": "error", "error": "email " + msg}
        return util.json_response(result)

    about, msg = util.check_string(about, maxlen=256)
    if about is None:
        result = {"status": "error", "error": "about " + msg}
        return util.json_response(result)

    r = g.redis

    if password:
        password, msg = util.check_string(password, config.PasswordMinLength)
        if not password:
            result = {"status": "error", "error": "password " + msg}
            return util.json_response(result)

        salt = g.user.get("salt", util.get_rand())
        r.hmset("user:"******"id"], {"password": util.hash_password(password, salt), "salt": salt})

    r.hmset("user:"******"id"], {"about": about.rstrip(), "email": email})
    return util.json_response({"status": "ok"})
Exemplo n.º 44
0
def user_login():
    username = request.values.get("username")
    password = request.values.get("password")

    hashed_password = hash_password(password)

    user_info = r_session.get("%s:%s" % ("user", username))
    if user_info is None:
        session["error_message"] = "用户不存在"
        return redirect(url_for("login"))

    user = json.loads(user_info.decode("utf-8"))

    if user.get("password") != hashed_password:
        session["error_message"] = "密码错误"
        return redirect(url_for("login"))

    if not user.get("active"):
        session["error_message"] = "您的账号已被禁用."
        return redirect(url_for("login"))

    session["user_info"] = user

    return redirect(url_for("dashboard"))
Exemplo n.º 45
0
Arquivo: user.py Projeto: yunt/crysadm
def user_login():
    username = request.values.get('username')
    password = request.values.get('password')

    hashed_password = hash_password(password)

    user_info = r_session.get('%s:%s' % ('user', username))
    if user_info is None:
        session['error_message'] = '用户不存在'
        return redirect(url_for('login'))

    user = json.loads(user_info.decode('utf-8'))

    if user.get('password') != hashed_password:
        session['error_message'] = '密码错误'
        return redirect(url_for('login'))

    if not user.get('active'):
        session['error_message'] = '您的账号已被禁用.'
        return redirect(url_for('login'))

    session['user_info'] = user

    return redirect(url_for('dashboard'))
Exemplo n.º 46
0
def registration():

    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = util.hash_password(request.form['password'])
        duplication = data_manager.check_username(username)
        registration_time = util.calculate_timestamp()
        duplication = data_manager.check_username(username)
        if len(duplication) != 0:
            message = 'username alredy exists '
            return render_template('registration.html', message=message)
        elif len(username) < 5:
            message = 'usernames must have at least 5 characters'
            return render_template('registration.html', message=message)
        elif len(request.form['password']) < 5:
            message = 'password must have at least 5 characters'
            return render_template('registration.html', message=message)
        else:
            message = 'you are succesfully registred'
            data_manager.update_users_registration(username, password,
                                                   registration_time)
            return render_template('registration.html', message=message)
    return render_template('registration.html')
Exemplo n.º 47
0
 def set_password(self, password):
     self.password_hash = util.hash_password(password)
Exemplo n.º 48
0
def user_register():
    email = request.values.get('username')
    invitation_code = request.values.get('invitation_code')
    username = request.values.get('username')
    password = request.values.get('password')
    re_password = request.values.get('re_password')

    r = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
    if re.match(r, email) is None:
        session['error_message'] = '邮箱地址格式不正确.'
        return redirect(url_for('register'))

    if username == '':
        session['error_message'] = '账号名不能为空。'
        return redirect(url_for('register'))

    if r_session.get('%s:%s' % ('user', username)) is not None:
        session['error_message'] = '该账号名已存在。'
        return redirect(url_for('register'))

    if password != re_password:
        session['error_message'] = '新密码输入不一致.'
        return redirect(url_for('register'))

    if len(password) < 8:
        session['error_message'] = '密码必须8位及以上.'
        return redirect(url_for('register'))

    if r_session.sismember('email', email):
        session['error_message'] = '该邮件地址已被注册.'
        return redirect(url_for('register'))

    if not r_session.sismember('invitation_codes', invitation_code) and \
            not r_session.sismember('public_invitation_codes', invitation_code):
        session['error_message'] = '无效的邀请码。'
        return redirect(url_for('register'))

    email_code = r_session.get('emailcode:%s' % email)
    if email_code is not None:
        code_time = json.loads(email_code.decode('utf-8'))
        if datetime.strptime(code_time, '%Y-%m-%d %H:%M:%S') + timedelta(minutes=5) > datetime.now():
            session['error_message'] = '发送邮件过于频繁 请稍候再试.'
            return redirect(url_for('register'))

    _chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    key = ''.join(random.sample(_chars, 36))
    user = dict(username=username, password=hash_password(password), id=str(uuid.uuid1()),
                active=True, is_admin=False, max_account_no=20, email=email,
                created_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

    r_session.setex('emailcode:%s' % email, json.dumps(user.get('created_time')), 60*5)
    r_session.setex('activecode:%s' % key, json.dumps(user), 60*30)

    bytesString = key.encode('utf-8')
    encodestr = base64.b64encode(bytesString)

    if user_email(email, encodestr.decode('utf-8')) != True:
        session['error_message'] = '激活帐户邮件发送失败 邮箱不存在.'
        return redirect(url_for('register'))

    r_session.srem('invitation_codes', invitation_code)
    r_session.srem('public_invitation_codes', invitation_code)

    session['info_message'] = '激活帐户邮件已发送到您的邮箱.'
    return redirect(url_for('register'))
Exemplo n.º 49
0
 def check_password(self, password):
     hashed, _ = hash_password(password, self.salt)
     return hashed == self.hashed_password
Exemplo n.º 50
0
def check_user_credentials(username, password):
    user = get_user_by_name(username)
    if not (user and user.has_key('password') and \
                user['password'] ==  util.hash_password(password, user['salt'])):
        return None, None
    return user['auth'], user['apisecret']
Exemplo n.º 51
0
def user_login(username, password):
    u = user.User.find_first('where name = ? and password = ?', username, hash_password(password))
    if u:
        return u.id
    else:
        return None