Exemplo n.º 1
0
    def post(self):  #performs authentication
        data = request.get_json()
        print(data)
        x = authenticate(data['username'], data['password'])
        if (x != None):
            print(x.id)
            state = 0

            mutex.acquire()
            if x.id in logged_in:
                state = 1
            else:
                logged_in.append(x.id)  #inserts userid into logged_in variable
                key_mapping[x.id] = secrets.token_hex(
                    16)  #initialises 16byte hex token and maps it to userid
            mutex.release()

            if state == 0:
                return {
                    "user_id": x.id,
                    "key": key_mapping[x.id]
                }
                #returns userid and key values user for AES encryption(the key is the password) on client side
            else:
                return {
                    "already_logged_in": "True"
                }
        else:
            pass
Exemplo n.º 2
0
    def post(self):
        if not request.is_json:
            return {
                'message': 'Invalid request, content-type is not JSON',
                'success': False
            }, 400

        username = request.json.get('username')
        password = request.json.get('password')
        if not username:
            return {
                'message': 'Invalid request, no username specified',
                'success': False
            }, 400
        if not password:
            return {
                'message': 'Invalid request, no password specified',
                'success': False
            }, 400
        user = authenticate(username, password)
        if user:
            access_token = create_access_token(identity=user.username)
            return {
                'accessToken': access_token,
                "message": "Logged in",
                "success": True
            }, 200
        else:
            return {
                'message': 'Invalid username/password',
                'success': False,
            }, 401
 def update_operator_email(self, operator_entry, Operator_id):
     if int(Operator_id) == operator_entry["Operator_id"]:
         if authenticate(operator_entry["old_Email"],
                         operator_entry["Password"]):
             db = get_connection()
             cursor = db.cursor()
             update_query = "update OPERATOR set Email=%s where Operator_id=%s"
             try:
                 cursor.execute(update_query,
                                (operator_entry["new_Email"],
                                 operator_entry["Operator_id"]))
                 db.commit()
                 return {
                     "status": 201,
                     "message": "Operator's email-id updated successfully"
                 }
             except mysql.Error as err:
                 print("Failed to update entry: {}".format(err))
                 return {"status": 500, "message": str(err)}
             finally:
                 db.close()
         else:
             return {"status": 401, "message": "Unauthorised Access"}
     else:
         return {"status": 401, "message": "Unauthorised Access"}
Exemplo n.º 4
0
def login():
    username = connexion.request.headers['X-Username']
    password = connexion.request.headers['X-Password']

    authenticated = security.authenticate(username, password)

    if authenticated:
        return 'OK', '200', {'x-message': 'User successfully authenticated'}

    else:
        return 'Forbidden', '403', {'x-message': 'User not authenticated'}
Exemplo n.º 5
0
    def post(self):
        from security import authenticate
        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, required=True, help='Username cannot be empty!')
        parser.add_argument('password', type=str, required=True, help='Password cannot be empty!')
        args = parser.parse_args()

        user = authenticate(username=args.get('username'), password=args.get('password'))
        if user:
            token = create_access_token(identity=args.get('username'), fresh=True)
            return {'access_token': token}, 200
        return {'message': 'Cannot validate Username or Password!'}, 400    
Exemplo n.º 6
0
def login_post():
    username = request.form.get('username')
    password = request.form.get('password')
    remember = True if request.form.get('remember') else False

    user = authenticate(username, password)

    if user:
        session['username'] = user.username
        return redirect(url_for('admonconsile'))
    else:
        return redirect(url_for('login'))
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    return authenticate(username, password)
Exemplo n.º 8
0
    def post(self):
        data = UserLogin.parser.parse_args()

        if not data['username']:
            return {'message': 'Missing username'}
        if not data['password']:
            return {'message': 'Missing password'}

        user = authenticate(data['username'], data['password'])
        if user is None:
            return {'message': 'Invalid credentials'}

        access_token = create_access_token(identity=user.username)
        return {'access_token': access_token, "user": user.json()}
Exemplo n.º 9
0
def standard_route(param_map, route_validator, route_db, route_formatter, commands=None):
    method_map = {
        'PUT': 'create',
        'GET': 'read',
        'PATCH': 'update',
        'DELETE': 'delete',
        'VIEW': 'index',
        'POST': 'command',
    }

    if request.method == 'OPTIONS':
        logger.info('Handling OPTIONS request')
        response = flask.Response()
        response.headers.set('Allow', ','.join([
            'PUT', 'GET', 'PATCH', 'DELETE', 'VIEW', 'OPTIONS', 'POST',
        ]))
        return response

    if request.method not in method_map:
        logger.warning('Received request with invalid route: {model}::{method}'.format(
            model=request.path,
            method=request.method,
        ))
        return 'Invalid method', 400

    method = method_map[request.method]

    logger.info('Handling request: {model}::{method}'.format(
        model=request.path,
        method=method,
    ))

    if not security.authenticate(method):
        return security.err_response(method)

    if commands and method == 'command':
        return commands()

    params = {}
    for key, value in param_map[method].items():
        if value in request.args:
            params[key] = request.args.get(value)

    return standard_request(
        params=params,
        validator=route_validator.__dict__[method],
        db_call=route_db.__dict__[method],
        formatter=route_formatter.__dict__[method],
    )
Exemplo n.º 10
0
def login():
    if 'loginName' in session.keys():
        print "we're here"
        return render_template('forward.html')
    elif request.method == "POST":
        print "we're there"
        uname = request.form['uname']
        password = request.form['password']
        button = request.form['button']
        if button == "login" and authenticate(uname,password):
            print "NEWSTUFF"
            session['loginName'] = uname
            return render_template('forward.html')
        
    return render_template('login.html')
Exemplo n.º 11
0
    def post(self):
        data = request.get_json()
        username = authenticate(data['username'], data['password'])
        if (username != None):
            mutex.acquire()
            i = username.id
            if i in logged_in:
                logged_in.remove(i)  # removes username from logged_in list
            mutex.release()

            key_mapping[i] = "None"  # removex 16 byte hex token created

            return {"message": "successful"}
        else:
            return {"message": "invalid username or password"}
Exemplo n.º 12
0
    def post(self):
        username = request.json.get('username', None)
        password = request.json.get('password', None)
        if not username:
            return message("Missing username parameter"), 400
        if not password:
            return message("Missing password parameter"), 400

        user = authenticate(username, password)

        if user:
            accessToken = create_access_token(identity=username)
            return {'access_token': accessToken}, 200
        else:
            return message('Invalid Username or Password'), 401
Exemplo n.º 13
0
def login():
    if 'loginName' in session.keys():
        print "we're here"
        return render_template('forward.html')
    elif request.method == "POST":
        print "we're there"
        uname = request.form['uname']
        password = request.form['password']
        button = request.form['button']
        if button == "login" and authenticate(uname, password):
            print "NEWSTUFF"
            session['loginName'] = uname
            return render_template('forward.html')

    return render_template('login.html')
Exemplo n.º 14
0
def login():
    request_data = request.get_json()
    signup_object = authenticate(request_data['email'],
                                 request_data['password'])
    token = encode_auth_token(signup_object.email)
    '''for val in result:
        try:
            if val.email == request_data['email']:
                if val.password == request_data['password']:
                    return {"message": "Login Successfully"}, 200
                else:
                    raise Exception()
        except:
            return {"message": "User credentials doesn't match !!!"}, 200'''

    return {"message": token}, 200
def auth():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    if authenticate(username, password):
        access_token = create_access_token(identity=username)
        return jsonify(access_token=access_token), 200
    else:
        return jsonify({"msg": "Bad username or password"}), 401
Exemplo n.º 16
0
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        username = request.values.get('username')
        password = request.values.get('password')
        user = authenticate(username, password)
        if not user:
            logging.warn('Failed login attempt from IP: %s',
                         request.remote_addr)
            return render_template('404.html'), 404
        access_token = create_access_token(identity=username, fresh=False)
        response = redirect(request.args.get('next') or url_for('index'))
        session['access_token'] = access_token
        response.headers['Authorization'] = 'Bearer {}'.format(access_token)
        response.method = 'GET'
        response.json = jsonify(data={"access_token": access_token})
        return response
Exemplo n.º 17
0
def login():
    if not request.is_json:
        return jsonify({"message": "Missing JSON in request"}), 400

    email = request.json.get('email', None)
    password = request.json.get('password', None)
    if not email:
        return jsonify({"message": "Missing email parameter"}), 400
    if not password:
        return jsonify({"message": "Missing password parameter"}), 400

    user = authenticate(email, password)

    if not user:
        return jsonify({"message": "Bad email or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=email)
    return jsonify(access_token=access_token, user=user.json()), 200
Exemplo n.º 18
0
    def post(self):
        if not request.is_json:
            return {"message": "request malformed."}, 400

        username = request.json.get("username", None)
        password = request.json.get("password", None)

        if not username:
            return {"message": "Missing username"}, 400

        if not password:
            return {"message": "Missing password"}, 400

        user = authenticate(username, password)

        if not user:
            return {"message": "invalid login credentials"}, 401

        access_token = create_access_token(identity=user.id)
        return {"access_token": access_token}, 200
Exemplo n.º 19
0
    def post(self):
        request_data = request.get_json()
        username = request_data.get('username', None)
        password = request_data.get('password', None)
        # Notice that when returning a dictionary jsonify is not longer used
        # because the api takes care of the conversion.
        if not username:
            return {'message': 'Missing username parameter'}, 400
        if not password:
            return {'message': 'Missing password parameter'}, 400

        userid = authenticate(username, password)
        if userid:
            # Identity can be any data that is json serializable
            access_token = create_access_token(identity=userid)
            # By default 200 is send indicating status ok
            return access_token
        else:
            # 401 Unauthorized client error status
            return {'message': 'Bad username or password'}, 401
def user_login(username, password):

    try:
        conn = sqlite3.connect('user.db')
        c = conn.cursor()
        search = (username, )
        c.execute('SELECT * FROM users WHERE username=?', search)
        check = c.fetchone()
        if check is not None:
            c.execute('SELECT * FROM users WHERE username=?', search)
            stored_pass = c.fetchone()[1]
            true_hash = authenticate(stored_pass, password)

            if not true_hash:
                return False
            else:
                return True
    except KeyError:
        pass
    return False
Exemplo n.º 21
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    user = authenticate(username, password)
    if not user:
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=username,
                                       fresh=True,
                                       user_claims={"role": user.role})
    return jsonify(access_token=access_token), 200
Exemplo n.º 22
0
def admin():
    if not security.authenticate('admin'):
        return security.err_response('admin')

    return standard_route(
        param_map={
            'create': {
                'create': 'create',
                'read': 'read',
                'update': 'update',
                'delete': 'delete',
                'index': 'index',
                'command': 'command',
                'admin': 'admin',
            },
            'read': {
                'api_key': 'api_key',
            },
            'update': {
                'api_key': 'api_key',
                'create': 'create',
                'read': 'read',
                'update': 'update',
                'delete': 'delete',
                'index': 'index',
                'command': 'command',
                'admin': 'admin',
            },
            'delete': {
                'api_key': 'api_key',
            },
        },
        route_validator=validator.admin,
        route_db=db.admin,
        route_formatter=formatter.admin,
        commands=route_commands.admin,
    )
Exemplo n.º 23
0
def landing():
    if authenticate(request.form["username"], request.form["password"]):
        return jsonify({"message": "Authenticated"})
    else:
        return jsonify({"message": "Authentication Failed!!!"})
Exemplo n.º 24
0

from security import authenticate

authenticate("bob", "123")


Exemplo n.º 25
0
def authenticate(username, password):
    return sec.authenticate(username, password)
Exemplo n.º 26
0
def authenticate(username, password):
    return sec.authenticate(username, password)