Exemple #1
0
def add_user():
    # Check all required fields
    for field in ['email', 'password']:
        if field not in flask.request.json:
            raise InvalidUsage('Field {0} is mising.', status_code=422, enum='POST_ERROR')

    email = flask.request.json['email']
    password = flask.request.json['password']

    # Check if user already exists
    user = User.query.filter_by(email=email).first()
    if user is not None:
        db.session.close()
        raise InvalidUsage('User already exists', status_code=409, enum='USER_EXISTS')

    user = User(email, password)
    db.session.add(user)
    db.session.commit()

    response = {
        'message': 'Registration was successful',
        'username': '',
        'email': user.email,
        'auth_token': user.get_auth_token()
    }
    log.print_log(app.name, 'Registered new user {}'.format(user))
    return flask.make_response(jsonify(response), 200)
Exemple #2
0
    def new(self, school_id=None, form_id=None, permissions=[], roles=[]):
        if school_id is None:
            school_id = self.school.id

        password = fake.password()

        user = User(first_name=fake.first_name(),
                    last_name=fake.last_name(),
                    email=fake.email(),
                    password=password,
                    school_id=school_id,
                    username=fake.user_name(),
                    form_id=form_id)
        user.raw_password = password
        user.id = fake.random_int()

        if len(permissions) > 0:
            permission_query = Permission.query.filter(
                Permission.name.in_(permissions),
                Permission.school_id == school_id)
            [user.permissions.append(p) for p in permission_query]

        if len(roles) > 0:
            role_query = Role.query.filter(Role.name.in_(roles),
                                           Role.school_id == school_id)
            [user.roles.append(r) for r in role_query]
        return user
def facebook_authorized(resp):
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    session['oauth_token'] = (resp['access_token'], '')
    session['logged_in'] = True
    me = facebook.get('/me')
    user = User.query.filter_by(email=me.data['email']).first()
    if user is None:
        user = User(me.data['email'],'facebook',me.data['id'],resp['access_token'],me.data['name'],me.data['link'])
        db.session.add(user)
        db.session.commit()
        session['id'] = user.id
    else :
        user.access_token = resp['access_token']
        db.session.add(user)
        db.session.commit()

    session['id'] = user.id
    session['name'] = user.name

    """return 'Logged in as id=%s name=%s email=%s redirect=%s' % \
        (me.data['id'], me.data['name'], me.data['email'], request.args.get('next'))"""
    return redirect('/')
Exemple #4
0
def user_edit(request):
    if not request.user.is_super:
        return render_to_response("user_edit.html", {'error1': u'无权限'},
                                  context_instance=RequestContext(request))

    if request.method == 'POST':
        post = request.POST
        uid = post.get('uid', '')
        state = post.get('state', '')
        role = post.get('role', "1")
        name = post.get('name', '')
        if uid:
            User.objects.filter(pk=uid).update(
                role=role,
                first_name=name,
                is_active=True if state == '1' else False)
        return HttpResponseRedirect(reverse('user_list'))
    else:
        _get = request.GET
        uid = _get.get('uid', '')
        if uid:
            try:
                user = User.objects.get(pk=uid)
            except User.DoesNotExist:
                user = User()
        else:
            user = User()
            user.id = ''
        return render_to_response("user_edit.html", {
            'user_l': user,
            'id': user.id
        },
                                  context_instance=RequestContext(request))
    def test_get_by_id(self):
        """Get user by ID."""
        user = User('foo', '*****@*****.**')
        user.save()

        retrieved = User.get_by_id(user.id)
        assert retrieved == user
Exemple #6
0
def load_user_from_request(request):

    # first, try to login using the api_key url arg
    api_key = request.args.get('api_key')
    if api_key:
        db = get_db()
        res = db.user.find_one({'openid': api_key})
        if res:
            user = User(res.get('openid'))
            return user

    # next, try to login using Basic Auth
    api_key = request.headers.get('Authorization')
    # print(api_key)
    if api_key:
        db = get_db()
        # api_key = api_key.replace('Basic ', '', 1)
        # try:
        #     import base64
        #     api_key = base64.b64decode(api_key).decode('utf-8')
        #     print(api_key)
        # except TypeError:
        #     pass
        res = db.user.find_one({'openid': api_key})
        print(res)
        if res:
            user = User(res.get('openid'))
            return user

    # finally, return None if both methods did not login the user
    return None
Exemple #7
0
def single_user(email):
    if User.objects(email=email).count() != 1:
        abort(404)
    user = User.objects().get(email=email)
    """
    args = {
        k: v[0] for (k, v) in request.args.items()
    }
    """
    db = client.cloakedhipster
    dbdiff = db.diff
    dbwindow = db.active_window

    query = {
        'user': user['id'],
    }

    if 'after' in request.args or 'before' in request.args:
        query['time'] = {}
        if 'after' in request.args:
            query['time']['$gte'] = long(request.args['after'])
        if 'before' in request.args:
            query['time']['$lte'] = long(request.args['before'])

    derped = list(dbdiff.find(query))
    derped2 = list(dbwindow.find(query))

    commits = get_num_commits()

    return render_template('user.html', commits=commits, userRaw=user.dict(), user=json.dumps(user.dict()), diffs=json.dumps(derped, cls=MongoJsonEncoder), actWindows=json.dumps(derped2, cls=MongoJsonEncoder))
Exemple #8
0
    def post(self):
        '''用户注册接口
            :return 返回注册信息{'re_code': '0', 'msg': '注册成功'}
        '''
        nickname = request.json.get('nickname')
        email = request.json.get('email')
        password = request.json.get('password')
        mailcode_client = request.json.get('mailcode')

        if not all([email, nickname, password, mailcode_client]):
            return jsonify(re_code=RET.PARAMERR, msg='参数不完整')

        # 从Redis中获取此邮箱对应的验证码,与前端传来的数据校验
        try:
            mailcode_server = redis_conn.get('EMAILCODE:' + email).decode()
        except Exception as e:
            current_app.logger.info(e)
            return jsonify(re_code=RET.DBERR, msg='查询邮箱验证码失败')
        if mailcode_server != mailcode_client:
            current_app.logger.info(mailcode_server)
            return jsonify(re_code=RET.PARAMERR, msg='邮箱验证码错误')

        user = User()
        user.email = email
        user.nickname = nickname
        user.password = password  # 利用user model中的类属性方法加密用户的密码并存入数据库
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            current_app.logger.info(e)
            db.session.rollback()
            return jsonify(re_code=RET.DBERR, msg='注册失败')
        # 6.响应结果
        return jsonify(re_code=RET.OK, msg='注册成功')
 def test_verify_password(self):
     pwd1 = "password1"
     pwd2 = "password2"
     user = User(email="*****@*****.**")
     user.set_password(pwd1)
     self.assertTrue(user.verify_password(pwd1))
     self.assertFalse(user.verify_password(pwd2))
Exemple #10
0
def list():

    from app.database import DataTable
    datatable = DataTable(
        model=User,
        columns=[User.remote_addr],
        sortable=[User.username, User.email, User.created_ts],
        searchable=[User.username, User.email],
        filterable=[User.active],
        limits=[25, 50, 100],
        request=request
    )

    if g.pjax:
        return render_template(
            'users.html',
            datatable=datatable,
            stats=User.stats()
        )

    return render_template(
        'list.html',
        datatable=datatable,
        stats=User.stats()
    )
    def post(self):
        result = {"status": False, 'msg': ''}
        status_code = 400
        if request.method == 'POST':

            email = request.json.get("email")
            first_name = request.json.get("first_name")
            last_name = request.json.get("last_name")
            password = request.json.get("password")

            user = User.query.filter_by(email=email).first()
            if user:
                result['msg'] = "User already exist!"
            else:
                user = User(email=email,
                            first_name=first_name,
                            last_name=last_name,
                            password=User.set_password_class_method(password))
                db.session.add(user)
                db.session.commit()
                status_code = 201
                result = {"status": True, 'msg': 'User created successfully.'}
        return Response(json.dumps(result),
                        status=status_code,
                        mimetype='application/json')
Exemple #12
0
def populate_db(num_users=5):
    """
    Fills the database with fake data.
    """
    from faker import Factory
    from app.user.models import User

    fake = Factory.create()

    admin_username = '******'
    admin_email = '*****@*****.**'
    admin_password = '******'

    users = []
    for _ in range(int(num_users)):
        users.append(
            User(fake.userName(), fake.email(),
                 fake.word() + fake.word(), fake.ipv4()))

    users.append(
        User(admin_username,
             admin_email,
             admin_password,
             fake.ipv4(),
             active=True,
             is_admin=True))

    for user in users:
        db.session.add(user)

    db.session.commit()
Exemple #13
0
    def test_get_by_id(self):
        """Get user by ID."""
        user = User('foo', '*****@*****.**')
        user.save()

        retrieved = User.get_by_id(user.id)
        assert retrieved == user
    def test_sanity(self):
        rv = self.app.post('/users', data=dict(email="*****@*****.**", password="******"))
        data = json.loads(rv.data)
        token = str(data['session_token'])
        rv = self.app.put(
            self.ENDPOINT + str(data['id']),
            data=dict(email="*****@*****.**", password="******"),
            headers={'X-Session-Token': token}
        )
        self.assertEqual(rv.status, "200 OK")
        user = User.get_by_email('*****@*****.**')
        self.assertIsNotNone(user)
        self.assertTrue(user.verify_password('_foobar_'))

        rv = self.app.put(
            self.ENDPOINT + str(data['id']),
            data=dict(email="*****@*****.**", password="******"),
            headers={'X-Session-Token': token}
        )
        self.assertEqual(rv.status, "200 OK")
        user = User.get_by_email('*****@*****.**')
        self.assertIsNotNone(user)
        self.assertTrue(user.verify_password('_foobar_new_'))
        self.assertFalse(user.verify_password('_foobar_'))
        self.assertIsNone(User.get_by_email('*****@*****.**'))
Exemple #15
0
def list():

    from app.database import DataTable
    datatable = DataTable(
        model=User,
        columns=[User.remote_addr],
        sortable=[User.username, User.email, User.created_ts],
        searchable=[User.username, User.email],
        filterable=[User.active],
        limits=[25, 50, 100],
        request=request
    )

    if g.pjax:
        return render_template(
            'users.html',
            datatable=datatable,
            stats=User.stats()
        )

    return render_template(
        'list.html',
        datatable=datatable,
        stats=User.stats()
    )
def current_user():
    args = token_parser.parse_args()
    token = args['X-Session-Token']
    valid, data = User.verify_session_token(token)
    g.user = None
    if valid:
    	if not data.get('password_reset'):
    		g.user = User.get_by_id(data.get('user_id'))
Exemple #17
0
    def set_up_users(self):
        self.admin = User(username="******", role=Role.Admin.value)
        self.moderator = User(username="******", role=Role.Moderator.value)
        self.user = User(username="******")
        self.user2 = User(username="******")

        self.add_all([self.admin, self.moderator, self.user, self.user2])
        self.commit()
 def test_get_by_email(self):
     email = "*****@*****.**"
     user = User.get_by_email(email)
     self.assertIsNone(user)
     User(email=email).put()
     user = User.get_by_email(email)
     self.assertIsNotNone(user)
     self.assertEqual(user.email, email)
Exemple #19
0
 def test_invalid_confirmation_token(self):
     u1 = User(username='******', email='*****@*****.**', password='******')
     u2 = User(username='******', email='*****@*****.**', password='******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     token = u1.generate_confirmation_token()
     self.assertFalse(u2.confirm(token))
Exemple #20
0
 def process(item):
     roles = item['roles']
     del item['roles']
     item['password'] = password_helper.generate_password_hash(
         item['password'])
     obj, msg = User(**item).create()
     roles = [Role.get_by_name(role) for role in roles]
     obj.roles = [UserRole(obj.id, role.id) for role in roles]
     obj.save()
Exemple #21
0
 def test_favorite_an_article(self):
     u1 = User('foo', '*****@*****.**')
     u1.save()
     p1 = UserProfile(u1)
     p1.save()
     article = Article(p1, 'title', 'some body', description='some')
     article.save()
     assert article.favourite(u1.profile)
     assert article.is_favourite(u1.profile)
Exemple #22
0
    def create_admin(email, name, password):
        user = User(email=email,
                    email_confirmed=True,
                    name=name,
                    role=UserRole.ADMIN)
        user.password = password

        db.session.add(user)
        db.session.commit()
Exemple #23
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data,
                    password=form.password.data)

        user.save()
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)
Exemple #24
0
def regist():
    form = RegistForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data)
        user.generate()
        return redirect(url_for('.login'))
    return render_template('regist.html', form=form)
Exemple #25
0
 def get(self, userid=None):
     if userid != None:
         this_user = User.get_by_id(userid)
         if not this_user:
             return 'User not found', 404
         return ({'user': {'Id': this_user.id, 'username': this_user.username, 'email': this_user.email,
                           'role': this_user.role}},
                 {'message': 'Gets a specific user'}), 200
     else:
         return User.get_many()
def register():
    """Register new user."""
    form = RegisterForm(request.form, csrf_enabled=False)
    if form.validate_on_submit():
        User.create(username=form.username.data, email=form.email.data, password=form.password.data, active=True)
        flash('Thank you for registering. You can now log in.', 'success')
        return redirect(url_for('public.home'))
    else:
        flash_errors(form)
    return render_template('public/register.html', form=form)
Exemple #27
0
def create_user():
    data = request.json
    hashed_password = generate_password_hash(data['password'], method='sha256')
    user = User(**json.loads(json.dumps(request.json)))
    user.public_id = str(uuid.uuid4())
    user.password = hashed_password
    user.admin = False
    db.session.add(user)
    db.session.commit()
    return jsonify({'Message': 'User %s created' % user.name})
 def test_unauthenticated(self):
     rv = self.app.put(self.ENDPOINT + str(1), data=dict(email="*****@*****.**", password="******"))
     self.assertEqual(rv.status, "401 UNAUTHORIZED")
     self.assertIsNone(User.get_by_email('*****@*****.**'))
     rv = self.app.post('/users', data=dict(email="*****@*****.**", password="******"))
     data = json.loads(rv.data)
     rv = self.app.put(self.ENDPOINT + str(data['id']), data=dict(email="*****@*****.**", password="******"))
     self.assertEqual(rv.status, "401 UNAUTHORIZED")
     self.assertIsNotNone(User.get_by_email('*****@*****.**'))
     self.assertIsNone(User.get_by_email('*****@*****.**'))
 def test_user_exists(self):
     rv = self.app.post("/users", data=dict(email="*****@*****.**", password="******"))
     self.assertEqual(rv.status, "201 CREATED")
     self.assertTrue('session_token' in rv.data)
     self.assertIsNotNone(User.get_by_email("*****@*****.**"))
     rv = self.app.post("/users", data=dict(email="*****@*****.**", password="******"))
     self.assertEqual(rv.status, "400 BAD REQUEST")
     self.assertFalse('session_token' in rv.data)
     self.assertIsNotNone(User.get_by_email("*****@*****.**"))
     self.assertEqual(1, len(User.query().fetch(2)))
Exemple #30
0
    def get_user_from_ldap(self, username):
        """
        # 使用管理员账号与密码登陆ldap服务,查询用户
        # 是否存在,存在则用用户信息创建User实例。
        :param username:
        :return:
        """
        client = self.ldap_login("*****@*****.**",
                                 "JWPRj7pa^J#3NLZ3")
        try:
            result = client.search_s("OU=小帮规划,DC=xiaobang,DC=xyz",
                                     ldap.SCOPE_SUBTREE,
                                     "(cn={})".format(username))[0][1]
        except IndexError:
            return None
        except ldap.NO_SUCH_OBJECT:
            return None

        user = User()
        user.id = result.get("employeeID")[0].decode()
        user.name = result.get("name")[0].decode()
        user.display_name = result.get("displayName")[0].decode()
        user.email = result.get("mail")[0].decode()
        user.department = result.get("department")[0].decode()
        user.role = result.get("title")[0].decode()
        user.title = result.get("title")[0].decode()

        return user
Exemple #31
0
def validate_email(field, value, error):
    """Check that the email is in the correct format"""
    email = value.strip().lower()
    if not email:
        error(field, "Field cannot be empty")
    User.get_by_email(email)
    if User.get_by_email(email):
        error(field, "Sorry!! Email taken!")
    if not re.match(
            r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]{2,4}$', value):
        error(field, "Invalid Email")
 def post(self):
     args = password_confirm_post.parse_args()
     token = args['reset_token']
     password = args['password']
     valid, data = user_model.verify_session_token(token)
     if not valid or not data.get('password_reset'):
         api.abort(400, 'Reset token is invalid')
     user = user_model.get_by_id(data.get('user_id'))
     user.set_password(password)
     user.put()
     return '', 200
 def test_invalid_email(self):
     rv = self.app.post('/users', data=dict(email='*****@*****.**', password='******'))
     data = json.loads(rv.data)
     token = str(data['session_token'])
     rv = self.app.put(
         self.ENDPOINT + str(data['id']),
         data=dict(email="foobar"),
         headers={'X-Session-Token': token}
     )
     self.assertEqual(rv.status, '400 BAD REQUEST')
     self.assertIsNone(User.get_by_email('foobar'))
     self.assertIsNotNone(User.get_by_email('*****@*****.**'))
Exemple #34
0
def signup():
    form = SignupForm()
    if form.validate_on_submit():
        new_user = User(form.email.data, form.student_id.data, 'changeme')
        new_user.update_login_info(request.environ['REMOTE_ADDR'])
        db.session.add(new_user)
        db.session.commit()

        login_user(new_user)
        return redirect(request.args.get('next') or url_for('index'))

    return render_template('user/signup.html', form=form)
Exemple #35
0
def signup():
    form = SignupForm()
    if form.validate_on_submit():
        new_user = User(form.email.data, form.student_id.data, 'changeme')
        new_user.update_login_info(request.environ['REMOTE_ADDR'])
        db.session.add(new_user)
        db.session.commit()

        login_user(new_user)
        return redirect(request.args.get('next') or url_for('index'))

    return render_template('user/signup.html', form=form)
Exemple #36
0
def register():
    form = RegisterForm()

    if form.validate_on_submit():
        print("a")
        User.create_user(
            username=form.username.data,
            email=form.email.data,
            password=form.password.data,
        )
        flash("You have registered")
        return redirect(url_for(".index"))
    return render_template("register.html", form=form)
Exemple #37
0
def register():
    """Register new user."""
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        User.create(username=form.username.data,
                    email=form.email.data,
                    password=form.password.data,
                    active=True)
        flash('Thank you for registering. You can now log in.', 'success')
        return redirect(url_for('public.home'))
    else:
        flash_errors(form)
    return render_template('public/register.html', form=form)
Exemple #38
0
 def decorated(*args, **kwargs):
     token = None
     if 'access-token' not in request.headers:
         return {'message': 'Token is missing, login to get token'}, 401
     try:
         token = request.headers['access-token']
         this_user_id = User.decode_auth_token(token)
         current_user = User.get_by_id(this_user_id)
         if not current_user:
             return {"message": "You are not logged in"}, 401
     except Exception as e:
         return {'message': 'Token is invalid or Expired!'}, 401
     return f(current_user, *args, **kwargs)
Exemple #39
0
def register():
    form = RegisterForm()
    if (form.validate_on_submit()):
        new_account = User()
        new_account.fullname = form.name.data
        new_account.username = form.username.data
        new_account.password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        db.session.add(new_account)
        db.session.commit()
        return 'account made'

    return render_template('register.html', form=form)
Exemple #40
0
def user_register():
    data = json.loads(request.data)        
    errors = validate(username = data['username'], email = data['email'], password = data['password'])
    if len(errors) == 0:
        user = User(data['username'], data['email'])
        user.set_password(data['password'])
        db.session.add(user)
        try:
            db.session.commit()
        except Exception, e:
            return jsonify(result = 'error', exists = True)
        login.login_user(user)
        return jsonify(result = 'success', user = user.json())
Exemple #41
0
def signup():
    if current_user.is_authenticated:
        return redirect(url_for('post.index'))
    form = SignUpForm()
    message = None
    if form.validate_on_submit():
        username = form.username.data.capitalize()
        email = form.email.data.capitalize()
        password = form.password.data

        # Check if other user has this email or username
        user_email = User.get_by_email(email)
        user_name = User.query.filter_by(username=username).first()
        if user_email is not None or user_name is not None:
            if user_email is not None:
                message = f'The email {email} already registered'
            else:
                message = f'Username {username} already taken'
        else:
            # Create user and save it
            user = User(username=username, email=email)
            user.set_password(password)
            user.save()
            if user.id == 1:
                user.admin = True
                db.session.commit()
            # Log in the user
            login_user(user, remember=True)
            next_page = request.args.get('next', None)
            if not next_page or url_parse(next_page).netloc != '':
                next_page = url_for('post.index')
            flash('Welcome to Micro-Posting')
            return redirect(next_page)
    return render_template('session/Signup.html', form=form, message=message)
Exemple #42
0
def createUser():
    name = request.form.get('name')
    email = request.form.get('email')
    role_id = request.form.get('role')
    usr = User(name, email, role_id)
    id = usr.create()
    message = {
        "data": {
            "status": "success",
            "action": "create",
            "user": str(id)
        }
    }
    return jsonify(message), 201
 def test_403(self):
     rv = self.app.post('/users', data=dict(email="*****@*****.**", password="******"))
     data = json.loads(rv.data)
     token = str(data['session_token'])
     rv = self.app.post('/users', data=dict(email="*****@*****.**", password="******"))
     data = json.loads(rv.data)
     rv = self.app.put(
         self.ENDPOINT + str(data['id']),
         data=dict(email='*****@*****.**'),
         headers={'X-Session-Token': token}
     )
     self.assertEqual(rv.status, '403 FORBIDDEN')
     self.assertIsNone(User.get_by_email('*****@*****.**'))
     self.assertIsNotNone(User.get_by_email('*****@*****.**'))
Exemple #44
0
    def post(self):
        req_data = request.get_json()
        if not 'new_password' in req_data or not 'confirm_new_password' in req_data:
            return {'message': "Make sure to fill all required fields"}, 400
        else:
            password = req_data['password']
            new_password = req_data['new_password']
            confirm_new_password = req_data['confirm_new_password']
            auth_header = request.headers['access_token']

            auth_token = request.headers['access-token']
            this_user_id = User.decode_auth_token(auth_token)
            if auth_header:
                try:
                    #auth_token = auth_header.split(" ")[1]
                    auth_token = request.headers['access-token']
                    user_id = User.decode_auth_token(auth_token)
                except IndexError:
                    return response('failed', 'Provide a valid auth token',
                                    403)
                else:
                    decoded_token_response = User.decode_auth_token(auth_token)
                    if not isinstance(decoded_token_response, str):
                        this_user = User.get_by_id(user_id)
                        user = User.query.filter_by(
                            username="******").first()
                        print(">>>>>>>>>>>>>>>>>>>>>", user)
                        print(
                            bcrypt.check_password_hash(
                                user.password, password.encode('utf-8')))
                        if bcrypt.check_password_hash(
                                this_user.password, password.encode('utf-8')):
                            if new_password != confirm_new_password:
                                return response('failed',
                                                'New Passwords do not match',
                                                400)
                            if not len(new_password) > 4:
                                return response(
                                    'failed',
                                    'New password should be greater than four characters long',
                                    400)
                            this_user.reset_password(new_password)
                            return response('success',
                                            'Password reset successfully',
                                            2001)
                        return response('success', 'Successfully logged out',
                                        2002)
                    return response('failed', decoded_token_response, 401)
            return response('failed', 'Provide an authorization header', 403)
Exemple #45
0
    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False

        if functions.is_email(self.email.data):
            user = UserModel.login_by_email(self.email.data, self.password.data)
        else:
            user = UserModel.login_by_username(self.email.data, self.password.data)

        if user == None:
            self.validation_errors.append('Email and password did not match.')
            return False
        self.user = user
        return True
 def put(self, object_id):
     user = user_model.get_or_404(object_id, message='User not found')
     if g.user != user and not g.user.admin:
         api.abort(403)
     args = users_put.parse_args()
     email = args['email']
     password = args['password']
     if email is not None and user.email != email:
         if user_model.get_by_email(email) is not None:
             api.abort(400, 'Email is already registered')
         user.email = email
     if password is not None:
         user.set_password(password)
     user.put()
     return '', 200
Exemple #47
0
def register():
    form = RegisterUserForm()
    if form.validate_on_submit():

        user = User.create(
            username=form.data['username'],
            email=form.data['email'],
            password=form.data['password'],
            remote_addr=request.remote_addr,
        )

        s = URLSafeSerializer(current_app.secret_key)
        token = s.dumps(user.id)

        send_registration_email.delay(user, token)

        flash(
            gettext(
                'Sent verification email to {email}'.format(
                    email=user.email
                )
            ),
            'success'
        )
        return redirect(url_for('index'))
    return render_template('register.html', form=form)
def create_user():
    try:
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']
        first_name = request.form['first_name']
        middle_name = request.form['middle_name']
        last_name = request.form['last_name']
    except KeyError as e:
        return jsonify(success=False,
                       message="%s not sent in the request" % e.args), 400

    user_type = "user"

    if '@' not in email:
        return jsonify(success=False,
                       message="Please enter a valid email"), 400

    cast = User.query.all()
    length = 1
    for cas in cast:
        length = length + 1

    user = User(first_name, middle_name, last_name, email, username, user_type,
                password)
    db.session.add(user)
    try:
        db.session.commit()
    except IntegrityError as e:
        return jsonify(success=False, message="This email already exists"), 400

    session['user_id'] = str(length)

    return redirect(url_for('user.check_login'))
    def post(self):
        args = password_reset_post.parse_args()
        email = args['email']
        user = user_model.get_by_email(email)
        if user is None:
            api.abort(404, 'User not found')
        token = user.get_session_token(expiration=21600, password_reset=True)
        if mail.is_email_valid(config.get('mail_sender')):
            sender = config.get('mail_sender')
        else:
            app_id = app_identity.get_application_id()
            sender = "%s <noreply@%s.appspotmail.com>" % (app_id, app_id)
        try:
            message = mail.EmailMessage()
            message.sender = sender
            message.subject = 'Password reset request'
            message.to = email
            message.body = '''
You're receiving this email because you requested a password reset.
Visit the following page to reset your password:

%s?reset_token=%s
''' % (config.get('password_reset_url'), token)
            message.send()
        except:
            api.abort(500)
        return '', 200
Exemple #50
0
def register():
    result = {}
    if request.method == 'GET':
        return render_template('res.html')

    if request.method == 'POST':
        username = request.values.get('username')
        password = request.values.get('password')
        email = request.values.get('email')
        if username and password and email:
            user = User.query.filter(User.username == username
                                     or User.email == email).all()
            if user:
                result.update(msg='账号或者邮箱已经存在', status=-2)
            else:
                user = User(username=username, password=password, email=email)
                db.session.add(user)
                db.session.commit()
                msg = Message("Hello",
                              sender="*****@*****.**",
                              recipients=['*****@*****.**'])
                mail.send(msg)
        else:
            result.update(msg='必要参数不能为空', status=-1)

    else:
        result.update(msg='错误的请求方式', status=400)
    return jsonify(result)
Exemple #51
0
def register():
    form = RegisterUserForm()
    if form.validate_on_submit():

        user = User.create(
            username=form.data['username'],
            email=form.data['email'],
            password=form.data['password'],
            remote_addr=request.remote_addr,
        )

        s = URLSafeSerializer(current_app.secret_key)
        token = s.dumps(user.id)

        send_registration_email.delay(
            {
                'username': user.username,
                'email': user.email
            }, token)

        flash(
            gettext(
                'Sent verification email to {email}'.format(email=user.email)),
            'success')
        return redirect(url_for('index'))
    return render_template('register.html', form=form)
Exemple #52
0
def signup():
    form = RegisterForm(form_type="inline")
    if form.validate_on_submit():
        #Form Values
        hashed_password = generate_password_hash(form.password.data, method='sha256')
        username = form.username.data
        email = form.email.data
        cur_check = db.engine.execute("SELECT email, username FROM users WHERE username='******' or email='{}'".format(username,email)).first()
        if cur_check is not None:
            error = Markup(
                '<div class="alert alert-danger w-100" role="alert">Der <b>Nutzername</b> oder die <b>Mailadresse</b> ist schon registriert</div>')
            return render_template('user/signup.html', form=form, error=error)
        else:
            new_user = User(username=username, email=email, password=hashed_password, lastname=form.lastname.data,
                            firstname=form.firstname.data, facility=form.facility.data, access=1,
                            business=form.business.data, confirmed=False)
            db.session.add(new_user)
            db.session.commit()

            token_user = token.generate_confirmation_token(username)
            confirm_url = "{}confirm/{}".format(Config.URL_ENDPOINT, token_user)
            html = render_template('user/activate_mail.html', confirm_url=confirm_url)
            subject = "Bitte bestätigen Sie ihre Email"
            mail = Mailer(email, subject, html)
            mail.send_email()
            login_user(User.query.filter_by(username=username).first())
            return render_template('user/signup.html')
    return render_template('user/signup.html', form=form)
Exemple #53
0
def user_exists(id):
    user_exists = False
    for user in User.select():
        user_id = "{}{}".format(user.id, user.salt)
        if user_id == str(id):
            user_exists = True
    return user_exists
Exemple #54
0
def newgroup(group_name):
    """
    Create a group
    """
    from app.user.models import User, Group
    g = Group(name=group_name)
    g.description = input('Enter a description of the group '
                          '(or leave blank for none): ') or None
    print(
        'Enter a list of initial user names to be added to the group, one on '
        'each line, ending with an empty line: ')
    users = []
    while True:
        username = input('> ')
        if not username:
            break

        user = User.get(username)
        if not user:
            print('Could not find user: {}'.format(username))
            continue

        if user in users:
            print('Heard you the first time.')
            continue

        users.append(user)

    g.members = users
    g.save()
Exemple #55
0
    def test_email_already_confirmed_redirect(self, db, testapp):
        with mail.record_messages() as outbox:
            res = testapp.get(url_for('auth.register'))
            form = res.forms['registerForm']
            form['username'] = '******'
            form['email'] = '*****@*****.**'
            form['password'] = '******'
            form['confirm'] = 'secret'
            form.submit()

            body_html = outbox[0].html

        groups = re.search('<a href=\"http://localhost(.*)\">', body_html)
        confirmation_url = groups[1]

        user = User.get_by_id(1)

        login_user(user)
        user.email_confirmed = True
        # FIXME: .get() has a different context. No logged in user
        response = testapp.get(confirmation_url)
        flashed_messages = get_flashed_messages()

        assert 'You have already verified your email address.' in flashed_messages
        assert response.status_code == 302
        assert urlparse(response.location).path == url_for('public.home')
Exemple #56
0
def edit_post():
    user = User.get(User.id == current_user.get_id())
    post_id = request.form["id"]
    content = request.form["content"]
    cleaned_markdown = clean_markdown(content)
    html = markdown.markdown(cleaned_markdown)
    result = user.edit_post(post_id, html)
    return result
Exemple #57
0
def get_home_page(commits):
    page = cache.get('homepage')
    if page is None:
        users = User.objects()
        page = render_template("home.html", users=users, commits=commits)
        cache.set('homepage', page, timeout=60)
        print 'rendered homepage'
    return page
 def post(self):
     args = login_post.parse_args()
     email = args['email']
     password = args['password']
     user = user_model.get_by_email(email)
     if user is None or not user.verify_password(password):
         api.abort(400, message='Wrong email or password')
     return user, 200
Exemple #59
0
def user_following(username = None):
    user = User.get_user_by_username(username)
    if user != None and user.is_active():
        return render_template('users/user_following.html',
            Follow = Follow,
            user = user,
            title = user.profile.name + " is following these pages.")
    abort(404)
Exemple #60
0
def user_followers(username = None):
    user = User.get_user_by_username(username)
    if user != None and user.is_active():
        return render_template('users/user_followers.html',
            Follow = Follow,
            user = user,
            title = user.profile.name + "'s Followers")
    abort(404)