Beispiel #1
0
def github_auth():
    """
    Github OAuth, redirects to github OAuth and obtains token using client id and secret
    :return:
    """
    if 'code' in request.args:
        github_url = 'https://github.com/login/oauth/access_token'
        data = {'client_id': client_id,
                'client_secret': client_secret,
                'code': request.args.get('code'),
                }
        headers = {'Accept': 'application/json'}
        r = requests.post(github_url, data=data, headers=headers)
        results = r.json()

        print(results)
        # Note: Once values are added to session, Flask will turn these into
        # a cookie that will be stored on the client side
        # (using set-cookie on header since cookies is not a valid header on
        # a response?)
        # Because of the secret key, values are stored with cryptography

        session['username'] = get_username(results.get('access_token'))
        session['code'] = request.args.get('code')

        # Import the user model and create a new instance of the object
        users = database.all('User')
        for user in users.values():
            if user.user_name == session['username']:
                session['id'] = user.id
                return redirect(url_for('user.homepage'))
        new_user = User(**({'user_name': session.get('username'), 'level_id': '100'}))
        new_user.save()
        session['id'] = new_user.id
        return redirect(url_for('user.homepage'))
Beispiel #2
0
def post_users():
    request_params = request.get_json()
    email = request_params.get('email')
    password = request_params.get('password')
    name = request_params.get('name')
    gender = request_params.get('gender')
    profile_image = request_params.get('profileImage')
    profile_image_id = request_params.get('profileImageId')

    q = db.session.query(User).filter(User.email == email)

    if q.count() > 0 :
        return jsonify(
            userMessage = "enrolled email"
        ), 400

    created_user = User(email=email,
                        password=password,
                        name=name,
                        gender=gender,
                        profile_image=profile_image,
                        profile_image_id=profile_image_id)

    db.session.add(created_user)
    db.session.commit()

    return jsonify(
        data=model_to_dict(created_user),
        token=created_user.get_token_string()
    )
def general_user(session):
    try:
        general_user = User.query.filter_by(
            google_id="*****@*****.**").first()
        assert not general_user

        general_user = User(google_id="*****@*****.**",
                            en_name="Hammington",
                            ko_name="Hee San",
                            entry_date=datetime.datetime(2017, 1, 1),
                            admin=False)
        session.add(general_user)

    except BaseException:
        general_user = User(google_id="*****@*****.**",
                            en_name="Hammington",
                            ko_name="Hee San",
                            entry_date=datetime.datetime(2017, 1, 1),
                            admin=False)
        general_user.google_id = str(random.randint(
            1, 1000)) + "_" + general_user.google_id
        session.add(general_user)

    session.commit()
    return general_user
Beispiel #4
0
 def post(self):
     data = request.get_json()
     user = User(username=data['username'])
     user.set_password(data['password'])
     db.session.add(user)
     db.session.commit()
     return "User " + user.username + " has been saved", 201
Beispiel #5
0
def sign_up():
    request_params = request.get_json()

    email = request_params.get('email')
    q = db.session.query(User) \
        .filter(User.email == email)
    if q.count() > 0:
        return jsonify(
            userMeesage="이미 가입되어있는 이메일 주소입니다."
        ), 409

    try:
        user = User()
        user = user.update_data(**request_params)
        db.session.add(user)
        db.session.commit()
        token = user.get_token()
        user_data = user.serialize()

        return jsonify(
            data=user_data,
            token=token
        ), 201
    except AttributeError:
        return jsonify(
            userMessage="요청 데이터의 키밸류가 바람직 하지 않습니다."
        ), 400
def set_default():

    record = User().query_record(id=1)

    if record: return {'code': 400, 'message': 'db has initialized'}, 400

    default_role = {
        'name': 'admin',
        'alias': '管理员',
        'status': 1,
    }

    role = Role.create_record(**default_role)

    default_user = {
        'name': 'David',
        'pwd': '123456',
        'status': 1,
        'role_id': 1
    }

    user = User.create_record(**default_user)

    return {
        'user': user.to_dict(rules=('-pwd', '-role')),
        'role': role.to_dict(rules=('-users', )),
    }, 201
Beispiel #7
0
def recommendation() -> Response:
    """Get insurance recommendation.

    :return: JSON response
    """
    # Get data from the request
    data = request.get_json()

    try:
        # Check if email is registered
        user: Optional[User] = User.find_by_email(data['email'])
        token: Optional[str] = request.headers.get('Authorization', None)

        # Update user data only if auth user has the same email as the one in the questionnaire
        if user and user.id == User.decode_auth_token(token):  # type: ignore
            user.first_name = data['first_name']
            user.address = data['address']
            user.children = data['children']
            user.occupation = data['occupation']
            user.update()

        # Get insurance recommendation
        insurance_list = Insurance.get_recommendation(data['occupation'],
                                                      data['children'])
    except Exception:
        return make_response(
            jsonify({'message': 'Failed to get recommendation.'}), 500)

    response_object = {
        'recommendations': insurance_schema.dump(insurance_list, many=True)
    }
    return make_response(jsonify(response_object), 200)
Beispiel #8
0
def register():
    form = RegistrationForm(request.form, meta={'locales': ['fa']})
    if request.method == 'POST' and form.validate():
        plain_email = re.match(re.compile("(.*)(@.*)"), form.email.data)
        user_email = plain_email.group(1).replace('.',
                                                  '') + plain_email.group(2)

        new_user = User(email=user_email, password=form.password.data)
        db.session.add(new_user)
        token = new_user.generate_confirmation_token()
        url = url_for('user.confirm', token=token, _external=True)
        try:
            email.send(
                new_user.email, 'Confirm Your Account',
                render_template('user/email/confirm.html',
                                user=new_user,
                                url=url))
            db.session.commit()
            new_user.add_ability(Abilities.TYPICAL)
        except ConnectionError:
            flash(
                u'.ارسال ایمیل تایید حساب کاربری با مشکل روبه رو شد.مجددا تلاش کنید'
            )
            db.session.rollback()
            return render_template('user/register.html', form=form)
        flash(u'.یک ایمیل تایید حساب کاربری برای شما ارسال شده است')
        return redirect(url_for('main.index'))
    return render_template('user/register.html', form=form)
Beispiel #9
0
def yelp_business_match():
    if 'Authorization' not in request.headers:
        abort(401)

    if not User().verify_key(request.headers.get('Authorization')):
        abort(401)

    if not request.is_json:
        abort(400)

    request_data = request.get_json(silent=True)
    if request_data is None:
        abort(400)

    if 'name' not in request_data or 'street_address' not in request_data or 'city' not in request_data \
            or 'state' not in request_data or 'country' not in request_data:
        return make_response(jsonify({'error': 'Missing required attributes'}),
                             400)

    user_id = User().get_user_id(request.headers.get('Authorization'))

    YelpData().yelp_request(yelp_request=request_data, user_id=user_id)

    data = YelpData().get_business_match_data(
        user_id=user_id,
        name=request_data['name'],
        address1=request_data['street_address'],
        city=request_data['city'],
        state=request_data['state'],
        country=request_data['country'])

    return jsonify(data)
Beispiel #10
0
    def post(self):
        current_user = get_jwt_identity()
        if current_user['role'] != 'system_admin':
            return {
                'status': STATUS_CODE['AUTH'],
                'message': 'Permission denied'
            }
        args = user.parse_args()
        isExists = User.objects(email=args['email']).first()
        if isExists:
            return {
                'status': STATUS_CODE['ERROR'],
                'message': 'Email already exists'
            }

        isExistsAccountNumber = User.objects(
            account_number=args['account_number']).first()
        if isExistsAccountNumber:
            return {
                'status': STATUS_CODE['ERROR'],
                'message': 'Account number already exists'
            }
        User(account_number=args['account_number'],
             balance=args['balance'],
             firstname=args['firstname'],
             lastname=args['lastname'],
             age=args['age'],
             gender=args['gender'],
             address=args['address'],
             employer=args['employer'],
             email=args['email'],
             city=args['city'],
             state=args['state']).save()
        return {'status': STATUS_CODE['SUCCESS'], 'message': 'Successfully'}
Beispiel #11
0
def sign_up():
    data = request.args
    email = data['email']
    password = data['password']
    user = User.find_user_by_email(email)

    if not user:
        try:
            user = User(email=email, password=password, username=email)

            db.session.add(user)
            db.session.commit()

            identity = {'email': user.email, 'name': user.username}

            access_token = create_access_token(identity=identity)
            response_object = {
                'status': 'success',
                'message': 'Successfully signed up',
                'auth_token': access_token
            }
            return make_response(jsonify(response_object)), 201
        except Exception as e:
            response_object = {
                'status': 'fail',
                'message': 'Could not create account',
                'error': ','.join(e.args)
            }

            return make_response(jsonify(response_object)), 500
    else:
        response_object = {'status': 'fail', 'message': 'User already exists'}
        return make_response(jsonify(response_object)), 400
Beispiel #12
0
def test_encode_auth_token_exception(test_client, throw_exception_encode_fix):
    """
    GIVEN an user id
    WHEN the encode_auth_token method is called and there's an exception
    THEN raise Exception
    """
    with pytest.raises(Exception):
        User.encode_auth_token(0)
Beispiel #13
0
def create():
    # TODO Change to request.is_json attribute (v0.11)
    if not request.json:
        abort(400)
    user = User(request.json['username'], request.json['password'])
    db.session.add(user)
    db.session.commit()
    return jsonify(user.to_dict())
Beispiel #14
0
    def test_password_recovery(self):
        u1 = User(username='******', email='*****@*****.**')
        db.session.add(u1)
        db.session.commit()

        token = u1.get_reset_password_token()
        verified_user = User.verify_reset_password_token(token)
        self.assertEqual(u1, verified_user)
Beispiel #15
0
def create_user(data):
    user_data = data['user']
    user = User(username=user_data['username'])
    db.session.add(user)

    for p in data['store_user_role_scopes']:
        user.update_permission(p)
    db.session.commit()
Beispiel #16
0
def test_decode_auth_token_expired_exception(test_client,
                                             throw_exception_expired_fix):
    """
    GIVEN an authentication token
    WHEN the decode_auth_token method is called and there's an ExpiredSignatureError exception
    THEN raise Exception
    """
    with pytest.raises(jwt.ExpiredSignatureError):
        User.decode_auth_token('string')
Beispiel #17
0
    def test_add_note(self):
        u1 = User(username='******', email='*****@*****.**')
        db.session.add(u1)
        db.session.commit()
        self.assertEqual(u1.notes.count(), 0)

        u1.add_note('test title', 'test description')
        self.assertEqual(u1.notes.count(), 1)
        self.assertEqual(u1.notes.filter_by(id=1).first().title, 'test title')
Beispiel #18
0
def sign_up():
    user = User(**sign_up_user_params())
    print(user.name)
    if user.save():
        access_token = create_access_token(identity=user.id)
        refresh_token = create_refresh_token(identity=user.id)
        return jsonify(access_token=access_token, refresh_token=refresh_token)
    else:
        return jsonify({"status": "usuário inválido"}), 404
Beispiel #19
0
def test_decode_auth_token_invalid_exception(
        test_client, throw_exception_invalid_token_fix):
    """
    GIVEN an authentication token
    WHEN the decode_auth_token method is called and there's an InvalidTokenError exception
    THEN raise Exception
    """
    with pytest.raises(jwt.InvalidTokenError):
        User.decode_auth_token('string')
Beispiel #20
0
def query_user (uid):

  try: 
    record = User().query_record(uid) 

    return jsonify(record.to_dict())

  except:
    return 'query failed', 404
Beispiel #21
0
def test_encode_auth_token_success(test_client_with_db):
    """
    GIVEN an user id in the database
    WHEN the encode_auth_token method is called
    THEN return JWT token
    """
    user = User.find_by_email('*****@*****.**')
    token = User.encode_auth_token(user.id)

    assert token is not None
Beispiel #22
0
 def get_user(self, code):
     token = self.get_token(code)
     path = "{}?access_token={}&scope={}".format(self.user_message_path,
                                                 token, 'user')
     result = json.loads(requests.get(path).content.decode("utf-8"))
     if result is not None and len(result) > Constant.TWO.value:
         user = User(result['id'], result['login'], result['url'],
                     result['avatar_url'])
         User.save(user)
     return jsonify(result)
def user_create():
    form = OpsUser(is_update=False)
    if form.validate_on_submit():
        user = User()
        user.password = "******"
        for field in form:
            if field.name not in ("csrf_token", "submit"):
                user.__setattr__(field.name, field.data)
        return redirect(url_for(".user_index"))
    return render_template("user_control/user_create.html", form=form)
def load_user(id):
    user = User()
    user.set_anonymous(False)
    user.set_active(True)
    user.set_authenticated(True)
    db = get_db()
    doc = db.fetch(id)
    user.fromJSON(doc.value)

    return user
    def setUp(self):
        self.app = create_app('testing')
        self.test_app = self.app.test_client()
        with self.app.app_context():
            db.create_all()

        user = User(first_name="Jimmy",
                    last_name="Cocopuff",
                    email="*****@*****.**",
                    password="******")
        with self.app.app_context():
            db.session.add(user)
            db.session.commit()

        user = User(first_name="Jimmy",
                    last_name="Cocobeans",
                    email="*****@*****.**",
                    password="******")
        with self.app.app_context():
            db.session.add(user)
            db.session.commit()

        item = Item(
            user_id=1,
            title="Tea Set",
            description="Antique Tea set",
            price=140.00,
            category="furniture",
            charity="Big Cat Rescue",
            charity_url="http://www.thisisatotallyligiturl.com",
            charity_score=4,
            charity_score_image=
            "https://d20umu42aunjpx.cloudfront.net/_gfx_/icons/stars/4stars.png",
            image="img.ul",
            auction_length=5)
        with self.app.app_context():
            db.session.add(item)
            db.session.commit()

        item = Item(
            user_id=1,
            title="Rocking Chair",
            description="Vintage wood rocking chair",
            price=40.00,
            category='furniture',
            charity='Big Cat Rescue',
            charity_url="http://www.thisisatotallyligiturl.com",
            charity_score=4,
            charity_score_image=
            "https://d20umu42aunjpx.cloudfront.net/_gfx_/icons/stars/4stars.png",
            image='img.ul',
            auction_length=5)
        with self.app.app_context():
            db.session.add(item)
            db.session.commit()
Beispiel #26
0
def users():
    try:
        if request.method == 'GET':   
            users = User.objects()
            return Response(users.to_json(), mimetype='application/json', status=200)
        elif request.method == 'POST':
            data = request.json
            user = User.create(data)
            login_user(user)
            return Response(user.to_json(), mimetype='application/json', status=200)
    except Error as e: return error(str(e))
Beispiel #27
0
 def post(self):
     data = self.reqparse.parse_args()
     try:
         user = User(email=data['email'], is_manager=data['is_manager'])
         user.set_password(data['password'])
         db.session.add(user)
         db.session.commit()
     except IntegrityError as e:
         db.session.rollback()
         return "Integrity error: " + str(e), 400
     return "User " + user.email + " has been saved", 201
Beispiel #28
0
def create_user (uname):
  
  try:
    user = User()
    user.name = uname
    record = user.create_record(uname)

    return jsonify(record.to_dict()), 201

  except:
    return 'create failed', 400
Beispiel #29
0
def test_decode_auth_token_success(test_client_with_db):
    """
    GIVEN a valid authentication token
    WHEN the decode_auth_token method is called
    THEN return the user id
    """
    # Prepare test
    user = User.find_by_email('*****@*****.**')
    token = User.encode_auth_token(user.id)

    payload_sub = User.decode_auth_token(token)

    assert payload_sub == user.id
Beispiel #30
0
def login(request):
    """
    处理登录请求
    """
    form = request.form()
    u = User(form)
    if u.validate_login():
        session_id = Session.new(u)
        headers = {
            'Set-Cookie': 'session_id={}; Path=/'.format(session_id)
        }
        return redirect('/twitter/twitter/index', headers)
    else:
        return redirect('/twitter/user/welcome')
Beispiel #31
0
    def setUp(self):
        self.app = create_app('testing')
        self.test_app = self.app.test_client()
        with self.app.app_context():
            db.create_all()

        user = User(first_name="Johnny",
                    last_name="McSellingstuff",
                    email="*****@*****.**",
                    password="******")
        with self.app.app_context():
            user.hash_password(user.password)
            db.session.add(user)
            db.session.commit()
Beispiel #32
0
    def post(self):
        email = request.json.get('email')
        password = request.json.get('password')
        if User.query.filter_by(email=email).first() is not None:
            abort(400, description='Email already in use')
        args = user_post_parser.parse_args()
        user = User(**args)
        user.hash_password(password)
        dt = trunc(datetime.now().timestamp())
        user.created_at = dt
        db.session.add(user)
        db.session.commit()

        return user
Beispiel #33
0
def check_and_create_user(data):
    response = dict()
    if data.validate_on_submit():
        existing_user = User.query.filter_by(email=data.email.data).first()
        if existing_user is None:
            user = User(name=data.name.data, email=data.email.data)
            user.set_password(data.password.data)
            db.session.add(user)
            db.session.commit()
            session["user_id"] = user.id
            response["message"] = "Successfully registered"
            response["redirect_to"] = "book.book_listing"

        return response
Beispiel #34
0
 def count_users_recursively(dep):
     dep_childs = cls.query.filter_by(parent_id=dep.id).all()
     count_users = 0
     for dep_child in dep_childs:
         count_users += User.count_users_in_department(dep_child.id)
         count_users += count_users_recursively(dep_child)
     return count_users
Beispiel #35
0
 def head_user_recursively(dep):
     if dep.user_id:
         return User.get_by_id(dep.user_id)
     if dep.parent_id:
         dep_parent = cls.query.filter_by(id=dep.parent_id).first()
         return head_user_recursively(dep_parent)
     return None
Beispiel #36
0
def add_user():
    _data = dict(request.form)
    _data['file'] = request.files['file']

    v = Validator(_data)
    v.field('name').required()
    v.field('surname').required()
    v.field('file').image()
    v.field('email').required().email()
    v.field('login').required()
    v.field('department').required()
    v.field('groups').required()
    v.field('mobile_phone').required().phone_number()
    v.field('birth_date').datetime(format='%d.%m.%Y')
    if v.is_valid():
        data = {
            'name': v.valid_data.name,
            'surname': v.valid_data.surname,
            'email': v.valid_data.email,
            'login': v.valid_data.login,
            'department': v.valid_data.department,
            'groups': v.valid_data.list('groups'),
            'mobile_phone': v.valid_data.mobile_phone,
            'skype': v.valid_data.skype,
            'birth_date': v.valid_data.birth_date,
            'photo': v.valid_data.file
        }

        already_used_login = User.get_by_login(data['login'])
        already_used_email = User.get_by_email(data['email'])

        if already_used_login:
            v.add_error('login', 'Такой логин уже занят')
        if already_used_email:
            v.add_error('email', 'Такой email уже занят')

        if already_used_login or already_used_email:
            return {"status": "fail", "errors": v.errors}

        try:
            create_user(**data)
            return {"status": "ok"}
        except DataProcessingError as e:
            return {'status': 'failOnProcess', 'error': e.value}

    return {"status": "fail", "errors": v.errors}
Beispiel #37
0
def edit_user(id):
    _data = dict(request.form)
    _data['file'] = request.files['file']

    v = Validator(_data)
    v.field('name').required()
    v.field('surname').required()
    v.field('file').image()
    v.field('email').required().email()
    v.field('department').required()
    v.field('inner_phone').integer(nullable=True)
    v.field('mobile_phone').required().phone_number()
    v.field('birth_date').datetime(format='%d.%m.%Y')
    if v.is_valid():
        edited_user = User.get_by_id(id)
        duplicate_error = False
        data = {
            'id': id,
            'full_name': "{0} {1}".format(v.valid_data.name, v.valid_data.surname),
            'email': v.valid_data.email,
            'department': v.valid_data.department,
            'mobile_phone': v.valid_data.mobile_phone,
            'inner_phone': v.valid_data.inner_phone,
            'position': v.valid_data.position,
            'skype': v.valid_data.skype,
            'birth_date': v.valid_data.birth_date,
            'photo': v.valid_data.file
        }

        user_with_same_email = User.get_by_email(data['email'])

        if user_with_same_email and user_with_same_email != edited_user:
            duplicate_error = True
            v.add_error('email', 'Такой email уже занят')

        if duplicate_error:
            return {"status": "fail", "errors": v.errors}

        try:
            update_user(**data)
            return {"status": "ok"}
        except DataProcessingError as e:
            return {'status': 'failOnProcess', 'error': e.value}

    return {"status": "fail", "errors": v.errors}
Beispiel #38
0
def post_users():
    email = request.files['email']
    password = request.files['password']
    backnumber = request.files['backnumber']
    name = request.files['name']
    info = request.files['info']
    q = db.session.query(User).filter(User.email == email)
    if q.count() > 0:
        return jsonify(
            userMessage="your email is already enrolled"
        )
    user = User(email=email, password=password, name=name,info=info, backnumber=backnumber)
    db.session.add(user)
    db.session.commit()
    return jsonify(
        data=model_to_dict(user),
        token=user.get_token_string()
    )
    def post(self):
        username = self.get_argument("username",None)
        password = self.get_argument("password",None)
        
        if not username or not password:
            # do something
            self.flash.error = "You must enter a username and password to proceed. Please try again."
            self.redirect("/login")
            return
        
        pw = hashlib.sha1(password).hexdigest()
        username = User.normalize(username)
        user = User.lookup(username)
        
        #check the password.
        if not user or user['password'] != pw:
            # do something
            self.flash.error = "Login not valid"
            self.redirect("/login")
            return
        
        # check if user is suspended.
        if user.is_suspended() :
            self.flash.error = "Sorry the account you specified has been suspended."
            self.redirect("/")
            return
          

        user.history.last_login = datetime.datetime.utcnow()
        Mongo.db.ui.users.update({'_id': username}, {
                                                    '$set' : {'history.last_login': user.history.last_login},
                                                    '$inc' : {'history.num_logins' : 1}
                                                    })        
        #add to the session.
        self.session['username'] = user._id
        #check keep_logged_in
        if self.get_argument("keep_logged_in", False) == "on" :
            self.session['keep_logged_in'] = True
        
        self.set_current_user(user)
        self.flash.notice = "Welcome, %s" % user._id
        forwardUrl = self.get_argument('next','/')
        self.redirect(forwardUrl)
Beispiel #40
0
def sign_up():
    request_params = request.get_json()
    email = request_params.get('email')
    password = request_params.get('password')
    name = request_params.get('name')
    group_id = request_params.pop('groupId')

    # TODO  regex, password validation need
    if email is None:
        return jsonify(
            userMessage="이메일 입력을 확인해주세요."
        ), 400

    if password is None:
        return jsonify(
            userMessage="비밀번호 입력을 확인해주세요."
        ), 400

    if name is None:
        return jsonify(
            userMessage="이름 입력을 확인해주세요."
        ), 400

    q = db.session.query(User) \
        .filter(User.email == email)

    if q.count() > 0:
        return jsonify(
            userMeesage="이미 등록된 이메일입니다."
        ), 409

    user = User.add(request_params)

    if user is None:
        return jsonify(
            userMessage="server error, try again"
        ), 400

    # user_group_relation 추가
    if group_id != 0:
        user_group_relation = UserGroupRelation(user_id=int(user.id), group_id=int(group_id))
    else:
        user_group_relation = UserGroupRelation(user_id=int(user.id))
    db.session.add(user_group_relation)
    db.session.commit()

    token = user.get_token()
    user_data = user.serialize()
    user_data['user_group_relation'] = user_group_relation.serialize()

    return jsonify(
        data=user_data,
        token=token
    ), 201
Beispiel #41
0
def get_user():
    if not g.get('user'):
        sid = request.cookies.get('sid', None)
        session = redis.get(sid)
        uid = None
        if session is not None:
            session = pickle.loads(session)
            uid = session.get('user', {}).get('id', None)
            touch(sid, session)
        g.user = User.get_by_id(uid) or AuthUser()
    return g.user
Beispiel #42
0
def _edit_user_at_local_db(id, full_name, position, department, photo,
                           email, mobile_phone, inner_phone, birth_date, skype):
    try:
        User.edit_user(
            uid=id,
            full_name=full_name,
            position=position,
            email=email,
            inner_phone=inner_phone,
            mobile_phone=mobile_phone,
            birth_date=birth_date,
            skype=skype,
            photo=photo
        )
        User.add_user2dep(
            dep_id=Department.get_by_name(department).id,
            user_id=id
        )
        return True
    except:
        return False
Beispiel #43
0
 def count_users_in_dep_tree(cls, dep_id):
     dep = cls.query.filter_by(id=dep_id).first()
     c_u = User.count_users_in_department(dep_id)
     def count_users_recursively(dep):
         dep_childs = cls.query.filter_by(parent_id=dep.id).all()
         count_users = 0
         for dep_child in dep_childs:
             count_users += User.count_users_in_department(dep_child.id)
             count_users += count_users_recursively(dep_child)
         return count_users
     c_u += count_users_recursively(dep)
     return c_u - 1
Beispiel #44
0
def get_list_users(dep_id, user_name):
    department = Department.get_by_id(dep_id)
    users = User.find_user(dep_id, user_name)
    users_list = []
    a = {"users":[]}
    for u in users:
        src_foto, dep_name = '', ''
        user = User.get_by_id(u.id)
        if user.photo:
            src_foto = user.photo.get_url('thumbnail')
        else:
            src_foto = '/static/img/no_photo.jpg'
        if u.department_id:
            dep_name = u.department.name or ''
        else:
            dep_name = ''
        a["users"].append({"u_id":u.id,
                           "full_name":u.full_name,
                           "dep_name":dep_name,
                           "src_foto":src_foto})
    return jsonify(**a)
Beispiel #45
0
def restore_post():
    v = Validator(request.form)
    v.field('email').required().email()
    if v.is_valid():
        email = request.form.get("email")
        user = User.get_by_email(email)
        if user:
            token = PasswordRestore.add_token(user)
            print(token)
            send_password_restore_ref.delay(user.email, user.full_name, token)
        return jsonify({"status": "ok"})
    return jsonify({"status": "fail",
                    "errors": v.errors})
Beispiel #46
0
def login(login, password):
    if ldap.bind_user(login, password):
        sid = request.cookies.get('sid', None)
        user = User.get_by_login(login)
        uid = user and user.id or None
        if sid and uid:
            session = {
                'create_datetime': datetime.datetime.now().isoformat(),
                'user': {'id': uid}
            }
            redis.set(sid, pickle.dumps(session))
            return True
    return False
Beispiel #47
0
def authenticate():
    """
    @apiVersion 1.0.0
    @apiGroup User
    @apiName Authenticate
    @apiDescription Authenticate an existing user or register a user using phone number.
    An activation code will be send to phone.
    @api {post} /v1/user/authenticate Authenticate an existing user or register a phone number
    @apiHeader {String} Content-Type =application/json JSON (application/json)

    @apiParam {String} phone Phone of the existing user.

    @apiSuccessExample Success-Response:
        HTTP/1.1 200 OK

    @apiSuccessExample Success-Response:
        HTTP/1.1 201 Created

    @apiUse BadRequest

    @apiSampleRequest http://example.com/api/v1/user/authenticate
    """
    phone = request.json['phone']

    try:
        user_obj = User.query.filter_by(phone=phone).one()
        user_obj.send_activation_code()

        return jsonify(), 200

    except NoResultFound:
        user_obj = User(phone=phone)
        db.session.add(user_obj)
        db.session.commit()
        user_obj.send_activation_code()

        return jsonify(), 201
Beispiel #48
0
def get_departments(parent_id=None):
    dep_list = []
    departments = db.session.query(Department).filter_by(parent_id=parent_id).all()
    for dep in departments:
        dep_dict = row2dict(dep)
        if dep_dict["user_id"] != 'None':
            user = User.get_by_id(dep_dict["user_id"])
            dep_dict["user"] = row2dict(user)
        print(dep_dict)
        dep_dict['dep_list'] = get_departments(dep.id)
        dep_list.append(dep_dict)
    if len(departments):
        return dep_list
    else:
        return None
Beispiel #49
0
def profile(user_id=None):
    user = auth.service.get_user() if user_id is None else User.get_by_id(user_id)
    if user is None:
        abort(404)
    user_department = Department.get_dep_if_user_head(user.id)
    count_users = ''
    if user_department:
        count_users = Department.count_users_in_dep_tree(user_department.id)
    if user.department_id:
        head_user = Department.get_head_user_in_dep_tree(user.department_id, user.id)
    else:
        dep = db.session.query(Department).filter_by(parent_id=None).first()
        head_user = Department.get_head_user_in_dep_tree(dep.id, user.id)
    return render_template('profile/profile.html', user=user,
                                                   user_department=user_department,
                                                   count_users=count_users,
                                                   head_user=head_user)
Beispiel #50
0
def update_user(id, full_name, position, department, photo,
                email, mobile_phone, inner_phone, birth_date, skype):
    old_login = User.get_by_id(id).login
    ldap_user_attr = {
        'mobile': mobile_phone,
        'telephoneNumber': inner_phone,
        'displayName': full_name,
        'mail': email
    }

    if not _edit_user_at_local_db(id, full_name, position, department, photo, email, mobile_phone, inner_phone, birth_date, skype):
        raise DataProcessingError('Произошла ошибка при обновлении пользователя в локальной базе данных')

    if not _edit_user_at_ldap(old_login, ldap_user_attr):
        db.session.rollback()
        raise DataProcessingError('Произошла ошибка при обновлении пользователя в каталоге LDAP')
    else:
        db.session.commit()
Beispiel #51
0
def _add_user_to_local_db(login, name, surname, email, department, photo,
                          mobile_phone, inner_phone, birth_date, skype):
    try:
        user = User()
        user.login = login
        user.full_name = "{0} {1}".format(name, surname)
        user.mobile_phone = mobile_phone
        user.inner_phone = inner_phone
        user.email = email
        user.department = Department.get_by_name(department)
        user.birth_date = birth_date
        user.skype = skype

        db.session.add(user)
        db.session.flush()

        p = user.photo = File.create(name='photo.png', module='users', entity=user)
        p.makedir()
        p.update_hash()
        image.thumbnail(photo, width=100, height=100, fill=image.COVER).save(p.get_path(sufix="thumbnail"))
        image.resize(photo).save(p.get_path())
        return True
    except:
        return False
Beispiel #52
0
def dep_users_json(dep_id):
    columns = []
    columns.append(ColumnDT('id', filter=_default_value))
    columns.append(ColumnDT('full_name', filter=_default_value))
    columns.append(ColumnDT('email', filter=_default_value))
    columns.append(ColumnDT('login', filter=_default_value))
    columns.append(ColumnDT('mobile_phone', filter=_default_value))
    columns.append(ColumnDT('inner_phone', filter=_default_value))
    query = db.session.query(User).filter_by(department_id=dep_id)
    rowTable = DataTables(request, User, query, columns)
    json_result = rowTable.output_result()
    departments = Department.get_all()
    for row in json_result['aaData']:
        row_id = row['0']
        last_columns = str(len(columns))
        dep_html = ''
        for dep in departments:
            sel = 'selected' if dep.id == dep_id else ''
            dep_html += "<option value='"+str(dep.id)+"/"+row_id+"' "+sel+">"+dep.name+"</option>"
        manage_html = """
          <select onchange="change_user_dep(this.value)" id="first-disabled" class="selectpicker" data-hide-disabled="true" data-live-search="true" data-width="200px">
            <optgroup label="Доп возможности">
              <option value="0/"""+row_id+"""">Удалить из отдела</option>
            </optgroup>
            <optgroup label="Отделы">"""+dep_html+"""</optgroup>
          </select>
          <script type="text/javascript">$('.selectpicker').selectpicker({style: 'btn-default',size: 5});</script>
          """
        row[last_columns] = manage_html
        src_foto = ''
        user = User.get_by_id(row_id)
        if user.photo:
            src_foto = user.photo.get_url('thumbnail')
        else:
            src_foto = '/static/img/no_photo.jpg'
        row['1'] = """<img src="{src}" class="foto-small-struct">""".format(src = src_foto) + "<a href='"+url_for('user.profile')+"/"+row_id+"'>"+row['1']+"</a>"
        head_dep = str(len(columns)+1)
        if Department.is_user_head(dep_id, int(row_id)):
            checked = "checked"
        else:
            checked = ''
        row[head_dep] = "<input onclick='change_head_dep(this, "+str(dep_id)+", "+row_id+")' type='checkbox' id='head_check' "+checked+">"
    return jsonify(**json_result)
 def post(self):
     username = self.get_argument("username",None)
     password = self.get_argument("password",None)
     
     if not username or not password:
         # do something
         self.flash.error = "You must enter a username and password to proceed. Please try again."
         self.redirect("/signup")
         return
     
     if password != self.get_argument("password2", None) :
         self.flash.error = "Passwords do not match. Please try again."
         self.redirect("/signup")
         return
     
     user = User.instance(username, password)
     Mongo.db.ui.users.insert(user)
     self.flash.info = "Successfully created your account, please log in."
     self.redirect("/login")
Beispiel #54
0
def reject_member(community_id, member_id):
    user = utils.auth.service.get_user()

    if not user.is_authorized:
        abort(403)

    community = Community.get(community_id)
    member = User.get(member_id)
    # cm = CommunityMember.query.filter(
    #     CommunityMember.user_id == member_id,
    #     CommunityMember.community_id == community_id).first()
    if not member or not community or community.owner != user:
        abort(404)

    # cm.status = cm.STATUS.REJECTED
    community.members.remove(member)
    db.session.commit()

    res = {'status': 'ok', 'user': {'status': CommunityMember.STATUS.TITLE[CommunityMember.STATUS.REJECTED]}}
    return jsonify(res)
Beispiel #55
0
def site_register():
    form = LoginForm()
    if form.validate_on_submit():
        try:
            user = User.objects.get(email=request.form['email'])
            if user:
                flash('This email address is already in use.', 'error')
            return render_template('site/login.html', form=form)

        except User.DoesNotExist:
            user = User()
            user.email = request.form['email']
            user.username = request.form['email']
            user.set_password(request.form['password'])
            user.save()

            flash('Successfully registered', 'success')
            return redirect(url_for('site_index'))
    return render_template('site/login.html', form=form)
Beispiel #56
0
def sign_up():
    request_params = request.get_json()
    email = request_params.get('email')
    password = request_params.get('password')

    # TODO  regex, password validation need
    if email is None:
        return jsonify(
            userMessage="이메일 입력을 확인해주세요."
        ), 400

    if password is None:
        return jsonify(
            userMessage="비밀번호 입력을 확인해주세요."
        ), 400

    q = db.session.query(User) \
        .filter(User.email == email)

    if q.count() > 0:
        return jsonify(
            userMeesage="already enrolled email"
        ), 409

    user = User.add(request_params)

    if user is None:
        return jsonify(
            userMessage="server error, try again"
        ), 400

    token = user.get_token()
    user_data = user.serialize()

    return jsonify(
        data=user_data,
        token=token
    ), 201
Beispiel #57
0
def register():
    form = RegisterForm()

    context = {
        'form': form
    }

    if request.method == 'POST' and form.validate_on_submit():
        user = User()
        user.email = form.email.data.strip().lower()
        user.password = form.password.data.strip()
        user.username = user.email

        db_session.add(user)
        db_session.commit()

        login_user(user)

        user.send_register_mail(request.host_url)

        return redirect(url_for("index.index"))

    return render_template("auth/register.html", **context)
Beispiel #58
0
def new_members():
    users = User.get_new()
    return render_template('user/new_members.html',  **{'users': users})
Beispiel #59
0
def set_rol_test(role_id, user_id):
    if role_id:
        User.set_user_role(user_id, role_id)
    else:
        User.set_user_is_admin(user_id)
    return jsonify({'status': 'ok'})
Beispiel #60
0
def set_user_to_dep(dep_id, user_id):
    User.add_user2dep(dep_id, user_id)
    return jsonify({'status': 'ok'})