예제 #1
0
    async def post(self):
        username = self.get_json_argument('username')
        password = self.get_json_argument('password')
        email = self.get_json_argument('email')
        code = self.get_json_argument('code')

        # check user exist
        user = User.select().where(User.username == username or User.email == email).limit(1)
        if len(user) > 0:
            raise JsonException(10001, 'username of email exist')

        # check verify code
        key = self.gen_verify_code_key(email)
        verify_code = await redis.get(key)
        verify_code = str(verify_code, 'utf-8')
        if verify_code != code:
            raise JsonException(10002, 'verify code is incorrect')

        hashed_password = password_hash(password)
        user = User(username=username, password=hashed_password, email=email)
        user.save()
        access_token = gen_access_token()
        auth = Auth(source_id=0, user_id=user.id, access_token=access_token)
        auth.save()
        self.finish_json(result={
            "user": user.to_dict(),
            'access_token': access_token
        })
예제 #2
0
def get_auth_token():
    #content type should be application/json
    data = request.get_json()
    username = data['username']
    password = data['password']
    authObj = Auth()
    login_response = authObj.login(username,password)
    if not login_response :
        return jsonify({'message' : 'Invalid username or password'})
    token = authObj.encode_auth_token(login_response['user_id'],login_response['is_admin'])
    return jsonify({ 'token' : token})
예제 #3
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        try:
            Auth.login(username, password)
            session['username'] = username
            return redirect(url_for('menu.getstart'))
        except ErrorHandlers.ErrorHandler as e:
            flash(e.message, 'error')

    return render_template('/login.html')
예제 #4
0
 def add_username_auth(self, uid, password):
     auth = Auth()
     auth.uid = uid
     auth.auth_hash = hashlib.md5(password).hexdigest()
     auth.auth_type = 0
     db.session.add(auth)
     try:
         db.session.commit()
         return auth
     except Exception as e:
         db.session.rollback()
         return abort(500,
                      u"注册用户失败, {0}".format(e))
예제 #5
0
 def post(self) -> Response:
     """Endpoint (public) is responsible for authenticating an end user.
     
     Returns:
         Response -- The Flask response object.
     """
     args = LOGIN_PARSER.parse_args()
     if Auth.authenticate(args['email'], args['password']) is not None:
         REST_LOGGER.info("auth/login -> Authenticated login for user %s",
                          args['email'])
         tokens = Auth.generate_tokens(args['email'])
         return make_response(jsonify(tokens), 200)
     REST_LOGGER.info("auth/login -> Denied login for user %s",
                      args['email'])
     return abort(401, "Invalid {email} or {password} given.")
예제 #6
0
def register():

    email = request.form.get("email")

    existing_user = User.query.filter(User.email == email).first()
    if existing_user:
        return jsonify({"error": "邮箱已经注册"}), 409

    password = request.form.get("password")
    password_hash = bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt(10))

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

    auth = Auth(user_id=user.id, password=password_hash)
    db.session.add(auth)
    db.session.commit()

    update_user_info(user)

    user_dict = user.to_dict(return_email=True)
    # TODO: sometimes create token failed due to connection
    # to redis, but user is already created, still return 200 OK
    # to client in this case
    token = create_token(user_dict)
    account_data = Account(token, user_dict).to_dict()
    return jsonify(account_data)
예제 #7
0
def projects():
    """ projects page """
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    r = requests.get(build_url('api/projects')).json()
    projects = r.get('projects')
    for project in projects:
        contributors = []
        for user_id in project.get("contributors"):
            r = requests.get(build_url(f"api/users/{str(user_id)}")).json()
            user_obj = ''
            if r.get('Status') == 'OK':
                user_obj = r.get('user')
                contributors.append(user_obj)
        project["contributors"] = contributors
        tech_list = []
        for tech_id in project.get("tech"):
            r = requests.get(build_url(f"api/tech/{str(tech_id)}")).json()
            tech_obj = ''
            if r.get('Status') == 'OK':
                tech_obj = r.get('tech')
                tech_list.append(tech_obj)
        project["tech"] = tech_list
    return render_template('projects.html', projects=projects, data=data)
예제 #8
0
def search():
    ''' search projects '''
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    query = str(request.form.get('searchBar')).lower()
    r = requests.get(build_url('api/projects')).json()
    projects = r.get('projects')
    matches = []
    for project in projects:
        if query == project.get('name').lower() or query in project.get(
                'name').lower():
            matches.append(project)
            continue
        if project not in matches:
            for user in project.get('users'):
                if query == user.lower() or query in user.lower():
                    matches.append(project)
                    break
            if project not in matches:
                for tech in project.get('technologies'):
                    if query == tech.lower() or query in tech.lower():
                        matches.append(project)
                        break
    msg = None
    if len(matches) == 0:
        matches = projects
        msg = f'{query} not found'
    # pub_data, auth_data, my_auth_data, my_role_auth_data
    return render_template('projects.html',
                           projects=matches,
                           msg=msg,
                           data=data)
예제 #9
0
def display_user_with_projects(request, user):
    from models.auth import Auth
    current_user = Auth.get_current_user()

    full_view = request.full_view
    tech_list = []
    if user and user.get('tech'):
        for tech_id in user.get("tech"):
            r = requests.get(build_url(f"api/tech/{str(tech_id)}")).json()
            tech_obj = ''
            if r.get('Status') == 'OK':
                tech_obj = r.get('tech')
                tech_list.append(tech_obj)
        user["tech"] = tech_list
    proj_list = []
    if user.get('projects'):
        for proj_id in user.get("projects"):
            r = requests.get(build_url(f"api/projects/{str(proj_id)}")).json()
            proj_obj = ''
            if r.get('Status') == 'OK':
                proj_obj = r.get('project')
                proj_list.append(proj_obj)
        user["projects"] = proj_list
    if current_user and current_user.get('id') == user.get('id'):
        current_user = user
    else:
        current_user = None
    data = {'user': user, 'current_user': current_user, 'full_view': full_view}
    return data
예제 #10
0
def index():
    """ about us page """
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    if request.current_user:
        return redirect(url_for('landing.dashboard'))
    return render_template('index.html', data=data)
예제 #11
0
def set_data_and_current_user():
    """
    check the current user and set it in data response
    """
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user}
    return data, current_user
예제 #12
0
def login_page():
    """ login page """
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {
        'current_user': current_user,
        'full_view': request.full_view,
    }
    return render_template('login.html', data=data)
예제 #13
0
def delete_account(id):
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {
        'current_user': current_user,
        'full_view': request.full_view,
        'msg': 'Account Deleted',
        'user': ''
    }
    return render_template('profile.html', data=data)
예제 #14
0
 def post(self) -> Response:
     """Endpoint (private) is responsible for generating the user new access tokens
     from their refresh tokens.
     
     Returns:
         Response -- The Flask response object.
     """
     REST_LOGGER.info("auth/refresh -> Refresh access token for user %s",
                      get_jwt_identity())
     return make_response(
         jsonify(Auth.generate_access_token(get_jwt_identity())), 200)
예제 #15
0
    def post(self):
        args = self.get_json_arguments()
        source = int(args.get("source_id", 0))
        username = args['username']
        password = args['password']

        if not username or not password:
            raise JsonException(1000, 'need username and password')

        pwd = password_hash(password)
        try:
            user = User.get(User.username == username)
        except:
            user = None
        if user is None or user.password != pwd:
            raise JsonException(1001, 'wrong password')
        access_token = gen_access_token()
        auth = Auth.single(
            Auth.source_id == source and Auth.user_id == user.id)
        if auth is None:
            auth = Auth(source_id=source, user_id=user.id)
        auth.access_token = access_token
        auth.save()

        self.finish_json(result={
            'user': user.to_dict(),
            'access_token': access_token
        })
예제 #16
0
 def get_current_user(self):
     username = self.request.headers.get('username')
     access_token = self.request.headers.get('Authorization')
     if username is None or access_token is None:
         return None
     user = User.single(User.username == username)
     if user is None:
         return None
     auth = Auth.single(Auth.source_id == 0 and Auth.user_id == user.id)
     if auth.access_token == access_token:
         return user
     else:
         return None
예제 #17
0
 def post(self) -> Response:
     """Endpoint (public) for registering a user account on the platform.
     
     Returns:
         Response -- The Flask response object.
     """
     args = REGISTER_PARSER.parse_args()
     if args['email'] == "":
         return abort(400, "The {email} field cannot be empty.")
     if args['fullname'] == "":
         return abort(400, "The {fullname} field cannot be empty.")
     if "@" not in args['email']:
         return abort(400, "The {email} specified is invalid.")
     if len(args['password']) < 6:
         return abort(400, "The {password} given must be >= 6 characters.")
     check_auth = Auth.get_by_email(args['email'])
     if check_auth is not None:
         REST_LOGGER.info(
             "auth/register -> Duplicate registration attempt for email %s",
             args['email'])
         return abort(409, "A user already exists with that {email}.")
     user_auth = Auth.create(args['email'], args['password'])
     if user_auth is None:
         REST_LOGGER.info(
             "auth/register -> Fail on Auth.create() with email %s",
             args['email'])
         return abort(
             401, "Failed to create an account with the given {email}.")
     user = User.create(args['email'], args['fullname'])
     if user is None:
         REST_LOGGER.error(
             "auth/register -> Fail on User.create() with email %s",
             args['email'])
         return abort(
             401, "Failed to create an account with the given {email}.")
     REST_LOGGER.info("auth/register -> User registered with email %s",
                      args['email'])
     return make_response(jsonify(Auth.generate_tokens(args['email'])))
예제 #18
0
def register():
    payload = request.get_json()
    password = payload["password"]
    password_hash = bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt(10))
    user_uuid = uuid.uuid4().hex
    user = User(uuid=user_uuid, name=get_rand_name())
    db.session.add(user)
    db.session.commit()
    user.uuid = str(user.id)
    auth = Auth(user_num_id=user.id, password=password_hash)
    db.session.add(auth)
    db.session.commit()

    token = create_token(user)
    account_data = Account(token, user.to_dict()).to_dict()
    return jsonify(account_data)
예제 #19
0
def register():
    payload = request.get_json()
    password = payload["password"]
    name = payload.get("name") or get_rand_name()
    password_hash = bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt(10))
    user = User(name=name)
    db.session.add(user)
    db.session.commit()

    auth = Auth(user_id=user.id, password=password_hash)
    db.session.add(auth)
    db.session.commit()

    token = create_token(user)
    account_data = Account(token, user.to_dict()).to_dict()
    return jsonify(account_data)
예제 #20
0
def users():
    """ users page """
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    r = requests.get(build_url('api/users')).json()
    users = r.get('users')
    for user in users:
        tech_list = []
        if user.get('tech'):
            for tech_id in user.get("tech"):
                r = requests.get(build_url(f"api/tech/{str(tech_id)}")).json()
                tech_obj = ''
                if r.get('Status') == 'OK':
                    tech_obj = r.get('tech')
                    tech_list.append(tech_obj)
            user["tech"] = tech_list
    return render_template('users.html', users=users, data=data)
예제 #21
0
 def put(self) -> Response:
     """Endpoint (private) responsible for updating a user's password.
     
     Returns:
         Response -- The Flask response object.
     """
     args = UPDATE_PARSER.parse_args()
     if len(args['new_password']) < 6:
         return abort(
             400, "Your {new_password} must be of length >= 6 characters.")
     auth = Auth.authenticate(get_jwt_identity(), args['old_password'])
     if auth is None:
         return abort(401, "Invalid credentials supplied.")
     auth.update_password(args['new_password'])
     auth.save()
     return make_response(
         jsonify(
             {"msg": "The user password has been successfully updated."}),
         200)
예제 #22
0
def register():
    """ about us page """
    # post request to api/users to create new one
    response = requests.post(build_url('api/users'), data=request.form).json()
    if response.get('status') == 'error':
        data = {'msg': response.get('message')}
        return render_template('login.html', data=data)
    print('user created')
    return start_session(request)
    # post to api/sessions
    # using user id from that, get user from /users
    # data dict with current_user = user
    # make response for profile.html with data
    # set cookie on response
    # return response
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    return render_template('login.html', data=data)
예제 #23
0
def user_profile(id):
    """ profile page """
    from models.auth import Auth
    if not id == request.current_user:
        r = requests.get(build_url(f"api/users/{str(id)}")).json()
        user = r.get('user')
    else:
        user = Auth.get_current_user()
    data = display_user_with_projects(request, user)
    if request.method == 'GET':
        return render_template('profile.html', data=data)
    # UPDATE users profile
    if request.method == 'POST':
        response = requests.put(build_url(f'api/users/{id}'),
                                data=request.form).json()
        if response.get('status') == 'error':
            data['msg'] = response.get('message')
            return render_template('profile.html', data=data)
        # do the update here
        return redirect(url_for('landing.user_profile', id=id))
예제 #24
0
def logout():
    """ logout route redirects to login page """
    from models.auth.session import Session
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {
        'current_user': current_user,
        'full_view': request.full_view,
    }
    cookie = request.cookies.get('session')
    if not cookie:
        return render_template('login.html', data=data)
    matching_session = Session.get_by_id(cookie)
    if not matching_session:
        return render_template('login.html', data=data)
    Session.delete_by_id(cookie)
    del Session.sessions[cookie]
    # delete request to api/sessions/<request.cookies>
    # data dict with current_user = user
    # make response with data
    # return response
    return render_template('login.html', data=data)
예제 #25
0
def all_projects():
    if request.method == 'POST':
        from models.auth import Auth
        current_user = Auth.get_current_user()
        f = request.form
        name = f.get('name')
        if Project.get_by_attr('name', name):
            return jsonify({'status': 'error', 'project': ''}), 400
        data = {
            'name': f.get('name'),
            'call_to_action': f.get('call_to_action'),
            'feature_backlog': f.get('feature_backlog'),
            'minimal_version': f.get('minimal_version'),
            'stretch_goals': f.get('stretch_goals')
        }
        new_project = Project(**data)
        new_project.save()
        return jsonify({'status': 'OK', 'project': new_project.to_dict()}), 200
    projects = Project.get_by_class()
    if len(projects) == 0:
        return jsonify({'status': 'error', 'projects': []}), 400
    return jsonify({'status': 'OK', 'projects': projects}), 200
예제 #26
0
from flask import Flask
from flask import request
from flask import jsonify
app = Flask(__name__)
from models.auth import Auth
from models.Movies import Movies

global authObj,movieObj
authObj = Auth()
movieObj = Movies()


@app.route('/')
def index():
    response_str = '''Please try one of the following URL :
                      to search GET /api/movies?param1=value1&param2=value2
                      to get a movie GET /api/movies/movie_id
                      to add a movie POST /api/movies
                      to edit a movie PUT /api/movies/movie_id
                      to delete a movie DELETE /api/movies/movie_id'''
    return response_str


@app.route('/api/movies',methods=['GET'])
def search_movie():
    #first creating API only to search on the basis of movie name,director and genre
    #add later searching based on imdb_score and 99_popularity, with lower than,greater than or equal to filter
    #this api created only for searching based on filter, and would not return anything if filter is not provided
    #if requried, if no params are sent, we can return first 10 results
    token_response = authObj.check_token(request)
    if  token_response == 'Token Expired' or token_response == 'Invalid token' or token_response == 'Token not found':
예제 #27
0
from hashlib import sha1
import hmac
import random
import codecs
import time
from urllib.parse import quote
import base64
import os
import models
from models.base import BaseNode, Base
from sqlalchemy import Column, String, Integer, ForeignKey
import json
import requests
from models.auth import Auth

auth = Auth()


class CustomNode(BaseNode, Base):
    """
    This model stores the needed data for the nodes
    """
    __tablename__ = 'custom_nodes'
    user_id = Column(String(60), ForeignKey('users.id'), nullable=False)
    name = Column(String(60))
    # Request or process
    work_type = Column(String(20), default='request')
    # Format 'GET https://example.com
    api_url = Column(String(100), default='')
    # Format 'users/{id}/nodes' this depends on self.data
    api_endpoint = Column(String(100), default='')
예제 #28
0
def some():
    from models.auth import Auth
    current_user = Auth.get_current_user()
    data = {'current_user': current_user, 'full_view': request.full_view}
    return render_template('dashboard.html', data=data)
예제 #29
0
파일: router.py 프로젝트: IU-dev/ais-eib
def init_route(app: Flask, db: DB):
    # Инициализация зависимостей для обработчиков
    news_repository = NewsRepository(db)
    user_repository = UserRepository(db)
    patient_repository = PatientRepository(db)
    record_repository = RecordRepository(db)
    auth = Auth(user_repository)

    # Переопределение стандартного рендера, добавляет параметр auth_user
    def render_template(*args, **kwargs):
        kwargs['auth_user'] = auth.get_user()
        return flask_render_template(*args, **kwargs)

    #Инициализация маршутов для API
    init_api_v1(app, news_repository, auth)

    @app.route('/')
    @app.route('/index')
    def index():
        last_news = news_repository.get_last(10)
        return render_template('index.html',
                               title='Главная | АИС ЭИБ',
                               last_news=last_news)

    @app.route('/install')
    def install():
        news_repository.install()
        user_repository.install()
        patient_repository.install()
        record_repository.install()
        return render_template('install-success.html',
                               title="Успешно | Установщик АИС ЭИБ")

    @app.route('/login', methods=['GET', 'POST'])
    def login():
        has_error = False
        login = ''
        if request.method == 'POST':
            login = request.form['login']
            if auth.login(login, request.form['password']):
                return redirect('/')
            else:
                has_error = True
        return render_template('login.html',
                               title='Вход | АИС ЭИБ',
                               login=login,
                               has_error=has_error)

    @app.route('/logout', methods=['GET'])
    def logout():
        auth.logout()
        return redirect('/')

    @app.route('/user', methods=['GET'])
    def user_list():
        user_list = user_repository.get_list()
        return render_template('user-list.html',
                               title='Список пользователей | АИС ЭИБ',
                               user_list=user_list)

    @app.route('/user/create', methods=['GET', 'POST'])
    def user_create_form():
        form = UserCreateForm(user_repository)
        if form.validate_on_submit():
            form.create_user()
            return redirect('/user')
        return render_template('user-create.html',
                               title='Создать пользователя | АИС ЭИБ',
                               form=form)

    @app.route('/record/<int:id>', methods=['GET'])
    def record_list_by_patient(id: int):
        record_list = record_repository.get_list_for_patient(id)
        patient = patient_repository.get_by_id(id)
        return render_template('record-list.html',
                               title='По пациенту ' + str(patient.name) +
                               ' | АИС ЭИБ',
                               record_list=record_list,
                               patient=patient)

    @app.route('/record/show/<int:id>')
    def record_show(id: int):
        record = record_repository.get_by_id(id)
        doctor = user_repository.get_by_id(record.doctor)
        patient = patient_repository.get_by_id(record.patient)
        return render_template('record-view.html',
                               title="Просмотр записи | АИС ЭИБ",
                               record=record,
                               doctor=doctor)

    @app.route('/record/create/<int:id>', methods=['GET', 'POST'])
    def record_create_form(id: int):
        form = RecordCreateForm(record_repository)
        if form.validate_on_submit():
            doc = auth.get_user()
            form.create_record(id, doc)
            return redirect('/record/' + str(id))
        return render_template('record-create.html',
                               title='Создать запись | АИС ЭИБ',
                               form=form,
                               id=id)

    @app.route('/user/delete/<int:id>')
    def user_delete(id: int):
        user = user_repository.get_by_id(id)
        user_repository.delete(user)
        return redirect('/user')

    @app.route('/patient', methods=['GET'])
    def patient_list():
        patient_list = patient_repository.get_list()
        return render_template('patient-list.html',
                               title='Список пациентов | АИС ЭИБ',
                               patient_list=patient_list)

    @app.route('/patient/create', methods=['GET', 'POST'])
    def patient_create_form():
        form = PatientCreateForm(patient_repository)
        if form.validate_on_submit():
            form.create_patient()
            return redirect('/patient')
        return render_template('patient-create.html',
                               title='Создать пациента | АИС ЭИБ',
                               form=form)

    @app.route('/patient/delete/<int:id>')
    def patient_delete(id: int):
        patient = patient_repository.get_by_id(id)
        patient_repository.delete(patient)
        return redirect('/patient')

    @app.route('/news', methods=['GET'])
    def news_list():
        news_list = news_repository.get_list()
        return render_template('news-list.html',
                               title="Новости | АИС ЭИБ",
                               news_list=news_list)

    @app.route('/news/create', methods=['GET'])
    def news_create_form():
        return render_template('news-create.html',
                               title="Новая новость | АИС ЭИБ")

    @app.route('/news/create', methods=['POST'])
    def news_create():
        if not auth.is_authorized():
            return redirect('/login')
        news = News(None, request.form['title'], request.form['content'],
                    auth.get_user().id)
        news_repository.create(news)
        return redirect('/news')

    @app.route('/news/<int:id>')
    def news_view(id: int):
        news = news_repository.get_by_id(id)
        user = user_repository.get_by_id(news.user_id)
        return render_template('news-view.html',
                               title="Просмотр новости | АИС ЭИБ",
                               news=news,
                               user=user)

    @app.route('/news/delete/<int:id>')
    def news_delete(id: int):
        news = news_repository.get_by_id(id)
        if news.user_id != auth.get_user().id:
            abort(403)
        news_repository.delete(news)
        return redirect('/news')
예제 #30
0
def before():
    from models.auth import Auth
    request.full_view, request.current_user = Auth.authenticate(request.url)