Beispiel #1
0
# =============================================================================
# Author: falseuser
# Created Time: 2019-08-26 15:31:19
# Last modified: 2019-08-26 15:31:57
# Description: api.py
# =============================================================================
from flask import Flask
from flask_restful import Api, Resource
from flask_httpauth import HTTPTokenAuth

APP = Flask(__name__)
API = Api(APP)
AUTH = HTTPTokenAuth(scheme='AUTH')


@AUTH.verify_token
def verify_token(token):
    print(token)
    if token == "11111":
        return True
    else:
        return False


class TestAPI(Resource):
    @AUTH.login_required
    def get(self):
        return 1


API.add_resource(TestAPI, "/test/")
Beispiel #2
0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadSignature, SignatureExpired

from app import account
from app.common import utils

# -H "Authorization: Token <jws-token>"
AUTH = HTTPTokenAuth(scheme='Token')


def create(username, expire):
    """
    create a token for account
    """
    token = Serializer(secret_key="secret_key", expires_in=expire) \
        .dumps({"user": username}) \
        .decode("utf-8")
    return token


@AUTH.verify_token
def verify(token):
    """
Beispiel #3
0
import redis
from google.oauth2 import id_token
from google.auth.transport import requests

conf = config('server',
              default={
                  'main_url': 'http://127.0.0.1:8080',
                  'max_count_per_query': 20,
                  'redis_host': 'localhost',
                  'redis_port': 6379,
                  'redis_prefix': 'memes_',
                  'google_client_id': 'Google client id'
              })

app = Flask(__name__)
auth = HTTPTokenAuth(scheme='Token')
cache = redis.StrictRedis(host=conf['redis_host'],
                          port=conf['redis_port'],
                          charset="utf-8",
                          decode_responses=True)


def get_google_id(token):
    try:
        id_info = id_token.verify_oauth2_token(token, requests.Request(),
                                               conf['google_client_id'])

        if id_info['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise ValueError('Wrong issuer.')
Beispiel #4
0
#coding:utf-8
'''
- token设置
'''
from flask_httpauth import HTTPTokenAuth
from flask import g

auth1 = HTTPTokenAuth(scheme='fCa1eb4cxjBkIuiVvK328qp6LEl79rsG')
tokens = {
    "Access_Key_SecretKey_1": "John-acce_Kye1123123CCaavcxwer",
    "Access_Key_SecretKey_2": "Susan_acce_Kye1123123CCaavcxwer"
}


@auth1.verify_token
def verify_token(token):
    g.user = None
    if token in tokens:
        g.user = tokens[token]
        return True
    else:
        return False
Beispiel #5
0
from flask import Flask, jsonify, request, redirect, make_response, g
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
basic_auth = HTTPBasicAuth()
auth = HTTPTokenAuth('Bearer') 
from werkzeug import secure_filename
import face_recognition as fr
from L6SOsgE6HT import users, tokens
import uuid
import cv2
import os
from web_utils import *
# from flasgger import Swagger, swag_from
from companies_view import companies_api

swagger_template = {
    'securityDefinitions': {
        'Bearer': {
            'type': 'apiKey',
            'name': 'Authorization',
            'in': 'header'
        }
    },
}

# HTTP basic auth
# Two separate auth, one for username and password for generating token
# Second for token for API endpoint

app = Flask(__name__, static_url_path='/static')
# swagger = Swagger(app, template=swagger_template)
app.register_blueprint(companies_api)
Beispiel #6
0
"""
    Token验证
"""
from collections import namedtuple

from flask import current_app, g, request
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired

from app.libs.scope import is_in_scope
from app.libs.wyy_exception import AuthFailedException, ForbiddenException

auth = HTTPTokenAuth(scheme='WYY')

User = namedtuple('User', ['uid', 'ac_type', 'scope'])


@auth.verify_token
def verify_token(token):
    user = verigy_auth_token(token)
    if not user:
        return False
    else:
        g.user = user
        return True


def verigy_auth_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
Beispiel #7
0
from flask import Blueprint, g
from flask_httpauth import HTTPTokenAuth

from app.models.participant import Participant

api_v1 = Blueprint('v1', __name__)
auth_basic = HTTPTokenAuth(scheme='Bearer')
auth_super = HTTPTokenAuth(scheme='Bearer')


@auth_basic.verify_token
def verify_basic_token(token):
    participant = Participant.verify_auth_token(token)
    if participant:
        g.user = participant
        g.token = token
        return True
    return False


@auth_super.verify_token
def verify_super_token(token):
    participant = Participant.verify_auth_token(token)
    if participant and participant.is_superuser:
        g.user = participant
        g.token = token
        return True
    return False


from . import participants, notifications, skills, auth
Beispiel #8
0
import secrets
import string
import sys

from flask import Flask, jsonify, request, json
from flask_cors import CORS
from flask_restful import Api, Resource, abort, reqparse
from flask_httpauth import HTTPTokenAuth
from flask_sqlalchemy import SQLAlchemy

import itsdangerous

app = Flask(__name__)
CORS(app)
api = Api(app)
auth = HTTPTokenAuth(header="X-Auth-Token")

app.config['SECRET_KEY'] = secrets.token_bytes(32)

if "SQLALCHEMY_DATABASE_URI" not in os.environ:
    os.environ["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["SQLALCHEMY_DATABASE_URI"]
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

if 'JOB_LOCATION' in os.environ:
    app.config['JOB_LOCATION'] = os.environ['JOB_LOCATION']

if 'SUBMISSION_LOCATION' in os.environ:
    app.config['SUBMISSION_LOCATION'] = os.environ['SUBMISSION_LOCATION']
Beispiel #9
0
#!/usr/bin/env python
import os
from flask import current_app as app
from flask import Flask, abort, request, jsonify, g, url_for
from .user_model import db, User
from . import user_controller
from . import rule_controller
from . import engine_controller
from time import gmtime, strftime
import datetime
from flask_httpauth import HTTPTokenAuth, HTTPBasicAuth, MultiAuth

auth = HTTPBasicAuth()
auth_token = HTTPTokenAuth('Bearer')
multi_auth = MultiAuth(auth, auth_token)


@auth.verify_password
def verify_password(username_or_token, password):
    return user_controller.test_password(username_or_token, password)


@auth_token.verify_token
def verify_token(username_or_token):
    return user_controller.test_token(username_or_token)


@app.route('/api/users', methods=['POST'])
def add_new_user():
    return user_controller.new_user()
Beispiel #10
0
from flask import g
from flask_httpauth import HTTPTokenAuth

auth = HTTPTokenAuth(scheme='Hcloud')

tokens = {"secret-token-1": "John", "secret-token-2": "Susan"}


@auth.verify_token
def verify_token(token):
    g.user = None
    if token in tokens:
        g.user = tokens[token]
        return True
    return False
Beispiel #11
0
import os
import sys
import operator
import json
import logging
import git
from settings import ROLES_DIR
import subprocess

from listroles import listRoles

from flask import Flask, make_response, request, Response, jsonify
from flask_httpauth import HTTPTokenAuth

app = Flask(__name__)
auth = HTTPTokenAuth("Token")


@auth.verify_token
def verify_token(token):
    return token == os.getenv("BY7_KEY")


@app.errorhandler(404)
def not_found(error=None):
    message = {
        'status': 404,
        'message': 'Not Found: ' + request.url,
    }
    resp = jsonify(message)
    resp.status_code = 404
Beispiel #12
0
from flask import jsonify, g
from app.models.user import User
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth

basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth('JWT')
multi_auth = MultiAuth(basic_auth, token_auth)


@basic_auth.verify_password
def verify_password(username, password):
    user = User.query.filter_by(username=username).first()
    if not user or not user.verify_password(password):
        return False
    g.auth_user = user
    return True


@token_auth.verify_token
def verify_token(token):
    if token:
        user = User.verify_token(token)
        if user:
            g.auth_user = user
            return True
        return False
    return False


@basic_auth.error_handler
def unauthorized(message=None):
Beispiel #13
0
from flask_debugtoolbar import DebugToolbarExtension
from flask_httpauth import HTTPTokenAuth, HTTPBasicAuth
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
# from flask_wtf import CSRFProtect
from flask_caching import Cache

db = SQLAlchemy()

migrate = Migrate()

bootstrap = Bootstrap()

toolbar = DebugToolbarExtension()

auth_token = HTTPTokenAuth()
auth_cms = HTTPBasicAuth()
auth_pa = HTTPBasicAuth()

cache = Cache(config={"CACHE_TYPE": "redis", "CACHE_REDIS_PASSWORD": ""})

# csrf = CSRFProtect()


def ext_init(app):
    db.init_app(app=app)
    migrate.init_app(app=app, db=db)
    bootstrap.init_app(app=app)
    # toolbar.init_app(app=app)
    cache.init_app(app=app)
    # csrf.init_app(app=app)
Beispiel #14
0
import os

import requests
from flask import Flask, current_app, g

from flask_httpauth import HTTPTokenAuth
from jose import JWTError, jwt

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret key here'
app.config['OAUTH_CLIENT_ID'] = 'your-registered-client-id'
app.config['OAUTH_CLIENT_SECRET'] = 'client-secret-returned-by-oauth-server'
app.config['OAUTH_JWT_PUB_KEY'] = os.environ.get('OAUTH_JWT_PUB_KEY')

jwt_auth = HTTPTokenAuth('Bearer')
introspect_auth = HTTPTokenAuth('Bearer')


@jwt_auth.verify_token
def verify_jwt_token(token):
    g.user = None
    try:
        claims = jwt.decode(token,
                            current_app.config['OAUTH_JWT_PUB_KEY'],
                            algorithms=['RS256'])
        g.user = claims['user']
        return True
    except JWTError:
        return False
    return False
Beispiel #15
0
api = Api(app)

# 关于flask SQLAlchemy实现ORM框架操作的一些基础配置
app.config['SECRET_KEY'] = 'dqwecf29vbneuirjnf2i3n0f2i302n'
# 数据库连接信息配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
# 是否自动提交sql执行
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
# 是否显示修改回执
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

# SQLAlchemy实例化
db = SQLAlchemy(app)
# 引入基础认证、token认证模块
auth = HTTPBasicAuth()
token_m = HTTPTokenAuth()
todos = [{
    "id": 0,
    "title": u'吃饭',
    "message": u'ab',
    "status": False,
    "add_time": u'0410',
    "end_time": u'0411'
}, {
    "id": 1,
    "title": u'睡觉',
    "message": u'sleep',
    "status": False,
    "add_time": time.time(),
    "end_time": None
}]
Beispiel #16
0
from flask import g
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from bucketlist import app
from bucketlist.models import User

auth_token = HTTPTokenAuth("Token")


def verify_password(username, password):
    """
    Login verification
    """
    g.user = User.query.filter_by(username=username).first()
    if not g.user:
        return False
    elif g.user.check_password(password):
        return g.user


def generate_auth_token(user_id, expires_in=3600):
    """
    Generates a token using the user's ID
    """
    signature = Serializer(app.config["SECRET_KEY"], expires_in=expires_in)
    return signature.dumps({"id": g.user.id})


@auth_token.verify_token
def verify_auth_token(token):
    """
from flask_httpauth import HTTPTokenAuth
from flask import jsonify, g

from app.models import User

# Setting up the Authorization header with a token profix

token_auth = HTTPTokenAuth("Bearer")

# Verifying the user security validity

@token_auth.verify_token
def verify_token(token):
    """ Verifies the user authentication token"""
    user_active_id = User.comfirm_token(token)
    if user_active_id:
        g.user = User.query.filter_by(id=user_active_id).first()
        return True
    return False

@token_auth.error_handler
def auth_error():
    """ Returns messege from unauthorised Access """
    return jsonify({"messege":"Access not Allowed, Invalid token"}), 401
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
auth = HTTPTokenAuth() #HTTPBasicAuth() # HTTPTokenAuth
from flask import jsonify, g, request

from .errors import unauthorized, forbidden
from ..models import User
from . import api

# auth必须要实现的装饰器,return True表示验证通过, nestjs也有这玩意
# 问题参数从头信息获取的,头信息用什么格式传呢? 要使用Basic Auth(不安全)
# @auth.verify_password
# def verify_password(email_or_token, password):
#     print(email_or_token)
#     if email_or_token == '' or email_or_token is None:
#         return False

#     print(email_or_token)

#     if password == '' or passowrd is None:
#         g.current_user = User.verify_auth_token(email_or_token)
#         g.token_used = True
#         return g.current_user is not None

#     user = User.query.filter_by(email = email).first()
#     if not user:
#         return False
#     # 写入上下文
#     g.current_user = user
#     g.token_used = False
#     return user.verify_password(password)
Beispiel #19
0
from flask import g
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
from BaseModel import Student

auth = HTTPBasicAuth()
auth2 = HTTPTokenAuth()

@auth.verify_password
def verify_password(username_or_token, password):
    user = Student.verify_auth_token(username_or_token)
    if not user:
        try:
            user = Student.get(Student.student_number == username_or_token)
        except:
            user = None
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True


@auth2.verify_token
def verify_token(token):
    user = Student.verify_auth_token(token)
    if user:
        g.user = user
        return True
    return False
Beispiel #20
0
import sys
from urllib.parse import urlparse

# Third-party imports...
from flask import Flask, abort, jsonify, request, make_response
from flask_httpauth import HTTPTokenAuth
from wtforms import Form, BooleanField, StringField, PasswordField, validators

# Local imports...
from .matrix_api import create_account
from . import config
from . import tokens

app = Flask(__name__)

auth = HTTPTokenAuth(scheme='SharedSecret')
logger = logging.getLogger(__name__)

re_mxid = re.compile(r'^@?[a-zA-Z_\-=\.\/0-9]+(:[a-zA-Z\-\.:\/0-9]+)?$')


def validate_token(form, token):
    """
    validates token

    Parameters
    ----------
    arg1 : Form object
    arg2 : str
        token name, e.g. 'DoubleWizardSki'
Beispiel #21
0
import datetime

from flask import Flask, jsonify, request, __version__ as flaskVersion
from flask_httpauth import HTTPTokenAuth

from environment import getDockerSecret
from judge import evaluate

app = Flask(__name__)
auth = HTTPTokenAuth(scheme="Bearer")
startDatetime = datetime.datetime.now()


@auth.verify_token
def verify_token(token):
    return token == getDockerSecret("judge_token")


@app.route("/status", methods=["GET", "POST"])
@auth.login_required
def status():
    data = {
        "flask_version": flaskVersion,
        "start_datetime": startDatetime.isoformat()
    }
    return jsonify(data), 200


@app.route("/judge", methods=["POST"])
@auth.login_required
def judge():
Beispiel #22
0
# -*- coding: utf-8 -*-
from flask import Flask
from flask_restful import Api
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
from flask_sqlalchemy import SQLAlchemy

from app.config import DATABASE, TOKEN_SCHEME

# API SERVER APPLICATION
app = Flask(__name__)
api = Api(app)

# DATABASE
app.config['SQLALCHEMY_ECHO'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)

# BASIC AUTH AUTHENTICATION
basic_auth = HTTPBasicAuth()

# TOKEN AUTH AUTHENTICATION
token_auth = HTTPTokenAuth(scheme=TOKEN_SCHEME)
"""

import sqlalchemy
import sqlalchemy.orm
import sqlalchemy.ext.declarative
from flask import Flask, g
from flask_restful import reqparse, Api, Resource
from flask_httpauth import HTTPTokenAuth


# Flask相关变量声明
app = Flask(__name__)
api = Api(app)

# 认证相关
auth = HTTPTokenAuth(scheme="token")
TOKENS = {
    "fejiasdfhu",
    "fejiuufjeh"
}


@auth.verify_token
def verify_token(token):
    if token in TOKENS:
        g.current_user = token
        return True
    return False


# 数据库相关变量声明
Beispiel #24
0
app.config['SECRET_KEY'] = 'the Nebula NCUHome'
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = '******'
app.config['MAIL_PASSWORD'] = '******'
app.config['TP_MAIL_SUBJECT_PREFIX'] = ['Team Planets']
app.config['TP_MAIL_SENDER'] = 'Team Planets Admin <*****@*****.**>'
app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://guest:123456@localhost/new?charset=utf8mb4'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
mail = Mail(app)
auth = HTTPTokenAuth(app)


class User(db.Model):
    __tablename__ = 'users'
    user_id = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
    user_name = db.Column(db.VARCHAR(16), nullable=False)
    user_email = db.Column(db.VARCHAR(64), nullable=False, unique=True)
    password_hash = db.Column(db.VARCHAR(200), nullable=False)
    user_token = db.Column(db.VARCHAR(200), nullable=False)
    user_active = db.Column(db.Boolean)

    @property
    def password(self):
        raise AttributeError('Password is not a readable attribute.')
Beispiel #25
0
import requests
from requests.auth import HTTPBasicAuth
import logging
import inspect
import hashlib

if sys.argv[0] != os.path.split(os.path.realpath(__file__))[1]:
    os.chdir(os.path.split(sys.argv[0])[0])
print("当前工作路径:" + str(os.getcwd()))
if not os.path.exists("log"):
    os.mkdir("log")

app = Flask(__name__)
app.static_folder
CORS(app, supports_credentials=True)
auth = HTTPTokenAuth(scheme='Bearer')
# app.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon.ico'))
ctx = app.app_context()
ctx.push()


def md5sum(filename):
    """
        用于获取文件的md5值
        :param filename: 文件名
        :return: MD5码
        """
    if not os.path.isfile(filename):  # 如果校验md5的文件不是文件,返回空
        return
    myhash = hashlib.md5()
    f = open(filename, 'rb')
Beispiel #26
0
from flask import Flask, g
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature

app = Flask(__name__) # 实例化Flask类
app.config['SECRET_KEY'] = 'mrsoft' # 设置秘钥
token_serializer = Serializer(app.config['SECRET_KEY'], expires_in=1800) # 实例化Serializer,设置过期时间
auth = HTTPTokenAuth('Bearer') # 基于Token的Bearer方式认证

@auth.verify_token
def verify_token(token):
    '''验证Token'''
    g.username = None
    try:
        data = token_serializer.loads(token) # 将Token反序列化为字典对象
    except SignatureExpired:  # Token 过期失效
        msg = 'token expired'
        app.logger.warning(msg)
        return False
    except BadSignature: # Token 错误
        msg = 'badSignature of token'
        app.logger.warning(msg)
        return False
    except:  # 其他错误
        msg = 'wrong token with unknown reason'
        app.logger.warning(msg)
        return False
    if 'username' in data: # 判断字典对象中是否包含username
        g.username = data['username']
        return True
Beispiel #27
0
from flask import g, current_app
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
from app.api.errors import error_response
from app.models import User

basic_auth = HTTPBasicAuth()

token_auth = HTTPTokenAuth()


@basic_auth.verify_password
def verify_password(username_or_token, password):
    #first try to authenticate by token
    user = User.verify_auth_token(username_or_token)
    if user is None:
        user = User.query.filter_by(username=username_or_token).first()
        if not user or not user.check_password(password):
            return False
    g.current_user = user
    return True


@basic_auth.error_handler
def basic_auth_error():
    return error_response(401)


@token_auth.verify_token
def verify_token(token):
    g.current_user = User.check_token(token) if token else None
            payload = {
                'token': auth_token,
                'sub': 'ethanee'
            }
            return {
                'status': 'success',
                'message': 'Token decoded.',
                'data': payload
            }
        except jwt.ExpiredSignatureError:
            return {
                'status': 'fail',
                'message': 'Signature expired.'
            }
        except jwt.InvalidTokenError:
            return {
                'status': 'fail',
                'message': 'Invalid token.'
            }


TOKEN_AUTH = HTTPTokenAuth()


@TOKEN_AUTH.verify_token
def verify_token(auth_token):
    response = OfficerAuthService.decode_auth_token(auth_token)
    token_data = response.get('data')
    if response.get('status') == 'success':
        return token_data.get('sub')
Beispiel #29
0
from flask import g, request, Blueprint
from flask_api import status
from flask_babel import gettext
from flask_httpauth import HTTPTokenAuth
from flask_login import current_user

from project.server import db
from project.server.main.serializers import CartSchema, CartItemSchema
from project.server.main.utils import error_response, validation_error, update_cart
from project.server.models import User, Cart, Product, CartItem
from project.server.user import admin_user_token

api_blueprint = Blueprint('api', __name__, url_prefix='/api')
api_blueprint.config = {}

auth = HTTPTokenAuth('Token')


@api_blueprint.record
def record_params(setup_state):
    """Make app config available in blueprint"""
    app = setup_state.app
    api_blueprint.config = dict([(key, value)
                                 for (key, value) in app.config.items()])


@auth.verify_token
def authenticate(token):
    """
    Combine session auth and token auth by checking token or current_user.
Beispiel #30
0
import bcrypt
from uuid import uuid4

import peewee
from playhouse.shortcuts import model_to_dict

from flask import g, current_app
from flask_httpauth import HTTPTokenAuth
import flask_principal as p
from flask_principal import Principal

from app import components

TOKEN_EXPIRATION = 30 * 24 * 60 * 60

auth_api = HTTPTokenAuth(scheme="Bearer")
principal = Principal(use_sessions=False, skip_static=True)


class Role(components.BaseRole):
    pass


class User(components.BaseUser):
    class Meta:
        table_name = "users"

    display_name = peewee.TextField(null=True)
    created = peewee.DateTimeField(null=False,
                                   default=datetime.now,
                                   formats=["%s"])