Esempio n. 1
0
def refreshToken():
    """Endpoint for getting refreshed JWT token by users
    ---
    responses:
        200:
            description: JWT Token
            content:
                text/plain:
                    schema:
                        type: string
        403:
            description: Not allowed
            content:
                application/json:
                    schema:
                        $ref: '#/definitions/Message'
    """
    try:
        token = parseToken(True)
        refreshToken = token.get('refreshToken')
        email = token.get('email')
        if refreshToken:
            user = UserService.findUser(email, {})
            tokenRepo = RefreshTokenRepository(getDb())
            if user and tokenRepo.exist(refreshToken, user.id):
                tokenRepo.delete(refreshToken)
                refreshToken = RefreshToken(user.id, str(uuid.uuid4()))
                tokenRepo.save(refreshToken)
                payload = user.toDict()
                payload['refreshToken'] = refreshToken.token
                return encodeJwt(payload), 200
    except Exception as e:
        current_app.logger.info(e)

    return {"message": "Not allowed"}, 403
Esempio n. 2
0
def decodeJwt(jwtString: str) -> dict:
    ET = jwt.JWT()
    ET.deserialize(jwtString)

    kid = ET.token.jose_header.get('kid')
    if kid == None:
        raise Exception('JWT invalid - kid not found')

    repo = KeyRepository(getDb())
    key = repo.findOne(kid)
    if key == None:
        raise Exception('JWT invalid - key with kid ' +
                        kid + ' does not exists')

    keyBytes = key.publicKey.encode('ascii')
    keyDecoded = jwk.JWK.from_pem(base64.b64decode(keyBytes))

    payload = json.loads(ET.token.objects.get('payload'))

    try:
        ET.deserialize(jwtString, keyDecoded)
    except jwt.JWTExpired as e:
        raise JWTExpiredException(e, payload)

    return payload
Esempio n. 3
0
def initDB():
    connection = db.getDb()

    db.destroyDb()
    db.initDb()
    with open('tests/db.json') as json_file:
        data = json.load(json_file)

        for dbName, rows in data.items():
            for row in rows:
                values = list(row.values())
                sql = "INSERT INTO `{}` (".format(dbName)
                sql += ",".join(row.keys())
                sql += ") VALUES (" + ', '.join((['%s'] * len(values)))+");"

                newVals = list()
                for val in values:
                    if type(val) is dict:
                        newVals.append(uuid.UUID(val.get('value')).bytes)
                    else:
                        newVals.append(val)
                with connection.cursor() as cursor:
                    cursor.execute(sql, newVals)

                connection.commit()
Esempio n. 4
0
def encodeJwt(payload: dict) -> str:
    payload['exp'] = (time.time() + 60*3)
    repo = KeyRepository(getDb())
    key = repo.findRandom()
    if key == None:
        raise Exception('Key collection seems to be empty!')

    keyBytes = key.privateKey

    keyDecoded = jwk.JWK.from_pem(base64.b64decode(keyBytes))

    Token = jwt.JWT(
        header={"alg": key.algorithm, 'kid': str(key.id)},
        claims=payload
    )
    Token.make_signed_token(keyDecoded)

    return Token.serialize()
Esempio n. 5
0
def login():
    """Endpoint for getting JWT token by users
    ---
    requestBody:
        required: true
        content:
            application/json:
                schema:
                    properties:
                        email:
                            type: string
                        password:
                            type: string
    definitions:
      Message:
        type: object
        properties:
          message:
            type: string
    responses:
        200:
            description: JWT Token
            content:
                text/plain:
                    schema:
                        type: string
        400:
            description: Invalid Request
            content:
                application/json:
                    schema:
                        $ref: '#/definitions/Message'
        403:
            description: Not allowed
            content:
                application/json:
                    schema:
                        $ref: '#/definitions/Message'
    """
    content = request.get_json(silent=True)
    if content == None:
        return {'message': 'Invalid request - no json'}, 400

    email = content.get('email')
    password = content.get('password')

    if email == None or password == None:
        return {'message': 'Invalid request'}, 400

    user = UserService.findUser(email, {"password": password})

    if user == None:
        return {'message': 'Login failed'}, 403

    current_app.logger.info(user)

    if user.isActive == False:
        return {'message': 'Please activate your account'}, 403

    refreshToken = RefreshToken(user.id, str(uuid.uuid4()))

    (RefreshTokenRepository(getDb())).save(refreshToken)

    payload = user.toDict()
    payload['refreshToken'] = refreshToken.token

    return encodeJwt(payload), 200