Exemple #1
0
 def do_controller_specific_work(self):
     phonenumber_regex = re.compile(r"\d{10}")
     result = phonenumber_regex.match(self.phonenumber)
     if result is None:
         raise API_Exception(400, "Invalid phone number")
     else:
         db_session = DB_Session_Factory.get_db_session()
         cfg = CFG.get_instance()
         if self.phonenumber != str(cfg.get('apple_tester', 'phone_number')):
             user = db_session.query(User).get(self.phonenumber)
             current_ts = datetime.now()
             if user is None:
                 user = User()
                 user.phonenumber = self.phonenumber
                 user.device_vendor_id = self.device_vendor_id
                 user.access_token = None
                 user.confirmation_token = self.generate_confirmation_token()
                 user.confirmation_deadline = current_ts + timedelta(minutes = 5)
                 user.last_request_ts = current_ts
                 db_session.add(user)
                 db_session.commit()
             else:
                 user.confirmation_token = self.generate_confirmation_token()
                 user.confirmation_deadline = current_ts + timedelta(minutes = 5)
                 user.last_request_ts = current_ts
            
                 db_session.add(user)
                 db_session.commit()
         
             message = "Your code is " + user.confirmation_token
             self.send_code_to_phone(code_message=message, to_number=user.phonenumber) 
         return HTTP_Response('200 OK', {'status' : 'SMS request sent'})
 def authenticate(self):
     auth_header = self.request_headers.get('AUTHORIZATION', None)
     if auth_header is not None:
         self.user = User.get_by_fb_access_token(auth_header)
         if self.user is None:
             fb_response = requests.get('https://graph.facebook.com/v2.0/me?access_token=' + auth_header)
             if fb_response.status_code is not 200:
                 raise Authorization_Exception("Unable to authenticate user with Facebook.")
             user_dict = fb_response.json()
             user = User(user_dict['id'], User.get_access_token(auth_header), user_dict.get('first_name', 'unknown_name'), user_dict.get('last_name', None))
             db_session = DB_Session_Factory.get_db_session()
             db_session.merge(user)
             db_session.commit()
             self.user = user
     else:
         raise Authorization_Exception("Unable to authenticate user. Please pass in authentication credentials via the Authorization header")
 def print_headers(self, authenticated_user):
     status_code = None
     for status_code_element in self.saml_response.iter("{urn:oasis:names:tc:SAML:2.0:protocol}StatusCode"):
         status_code = status_code_element.get('Value')
         if status_code != 'urn:oasis:names:tc:SAML:2.0:status:Success':
             self.print_forbidden_headers()
             return
     if status_code is None:
         self.print_forbidden_headers()
         return
     
     email = None
     # There really should only be one... but we'll loop through it anyway.
     for email_element in self.saml_response.iter('{urn:oasis:names:tc:SAML:2.0:assertion}NameID'):
         email = email_element.text
     if email is None:
         self.print_forbidden_headers()
         return
     
     user = User.refresh_user_session(email)
     print "Status: 303"
     print "Set-Cookie: session_id=" + user.session_id + "; Domain=onsite-inflight.com; Path=/"
     if self.type == "expense":
         self.relay_state = "expenses"
     if self.relay_state[0] is not '/':
         self.relay_state = '/' + self.relay_state
     print "Location: https://onsite-inflight.com" + self.relay_state
Exemple #4
0
def user_add():
    """
    fake = Faker()
    me = User(id=103, uuid=str(uuid.uuid4()), email=fake.email(),
                 password_hash='password',
                 access_token='asdasd',
                 refresh_token='asdasdasd',
                 created_at=datetime.now())
    db.session.add(me)
    db.session.commit()
    """
    if request.method == 'POST':
        #check_database = User.query.filter_by(email=request.form['email']).first()
        #if check_database:
        #    flash('Email is already exists')

        user = User(uuid=str(uuid.uuid4()),
                    email='emailyyy',
                    password_hash='password')
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('admin.user_main'))

    return render_template('admin/user/user_add_edit.html',
                           form=UserAddEditForm())
 def login(email, password):
     test = User.find_by_email_and_password(email=email, password=password)
     if test:
         access_token = create_access_token(identity=email)
         return jsonify(message='Login successful!',
                        access_token=access_token)
     else:
         return jsonify(message='Incorrect email or password'), 401
 def retrieve_password(email):
     user = User.find_by_email(email=email)
     if user:
         msg = Message('Your planetary password is ' + user.password,
                       sender="*****@*****.**",
                       recipients=[email])
         mail.send(msg)
         return jsonify(message='Password sent to ' + email)
     else:
         return jsonify(message='email does not exit'), 401
    def signin(email, password):
        user = User.objects(email=email).first()
        if user is None or user.verify_password(password) is False:
            raise AuthSigninException("User {} doesn't exist".format(email))
        if user is not None and user.verify_password(password):
            access_token = create_access_token(identity=email)
            refresh_token = create_refresh_token(identity=email)

            resp = jsonify({'Authorization': access_token})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp
def login():
    global user
    if request.method == 'POST':
        user = User.query.filter(
            User.name == request.form.get("yourname"),
            User.password == request.form.get("yourpw")).first()
        if user:
            login_user(user)
            return redirect('/')
        else:
            user = User()
    return render_template('get-started.html')
 def get_authenticated_user(self):
     if not CFG.get_instance().is_live():
         db_session = DB_Session_Factory.get_db_session()
         return db_session.query(User).get("*****@*****.**")
     try:
         cookie_string = os.environ['HTTP_COOKIE']
         cookie = Cookie.SimpleCookie(cookie_string)
         session_cookie = cookie['session_id'].value
     except (Cookie.CookieError, KeyError):
         session_cookie = None
     result = None
     return User.user_for_session_cookie(session_cookie)
def regist():
    global user
    if request.method == 'POST':
        if user.role != "admin":
            respone = {
                "errno": 200,
                "message": "Only the admin could add users"
            }
            data = json.dumps(respone)
            return data, 200, {"ContentType": "application/json"}
        params = json.loads(request.data)
        user_add = User()
        user_add.name = params["name"]
        user_add.password = params["password"]
        user_add.role = params["role"]
        db.session.add(user_add)
        db.session.commit()
        respone = {"errno": 200, "message": "creat user Success!!"}
        data = json.dumps(respone)
        return data, 200, {"ContentType": "application/json"}

    if request.method == 'GET':
        return render_template('regist.html', user=user)
    return render_template("404-error.html")
    def check_auth(self):
        if not CFG.get_instance().is_live():
            return None
        try:
            cookie_string = os.environ['HTTP_COOKIE']
            cookie = Cookie.SimpleCookie(cookie_string)
            session_cookie = cookie['session_id'].value
        except (Cookie.CookieError, KeyError):
            session_cookie = None
        result = None
        if session_cookie is None or User.session_is_active(session_cookie) is False:
            result = {'error' : 'authn_needed'}
            authn_request = """\
<?xml version="1.0" encoding="UTF-8"?>
<saml2p:AuthnRequest xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" AssertionConsumerServiceURL="http://onsite-inflight.com/api/post-sso" Destination="https://box.okta.com/app/template_saml_2_0/k5jimobgREMCSHKGRLVB/sso/saml" ForceAuthn="false" ID="%s" IsPassive="false" IssueInstant="%s" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Version="2.0">
    <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">http://onsite-inflight.com/api/post-sso</saml2:Issuer>
    <saml2p:NameIDPolicy AllowCreate="false" Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" SPNameQualifier="http://onsite-inflight.com/api/post-sso"/>
</saml2p:AuthnRequest>
""" % (uuid.uuid4().hex, datetime.now().isoformat())
            result['authn_request'] = base64.b64encode(authn_request)
        return result
def started():
    global user
    user = User()
    return render_template('get-started.html')
from argparse import ArgumentParser

from common import db
from config import DEF_ADDBLOCK
from login import userRoute
from model import create_app, Block
from flask_login import login_user
from flask import render_template, request, redirect

from model.record_model import Record
from model.user_model import User
from server.client_node import ClientNode
from server.client_node import current_block

DEFAULT_MODULES = [userRoute]
user = User()
app = create_app('../config.py')

for module in DEFAULT_MODULES:
    app.register_blueprint(module)


# 增加区块
def add_Block(patient, describe):
    global user
    global current_block
    timestamp = time.time()

    block = Block(timestamp=timestamp,
                  doctor=user.name,
                  patient=patient,
Exemple #14
0
from flask_restful import Api
from resources.challenge import Challenge
from resources.challenges import Challenges
from resources.days import Days
from model.user_model import db
from model.user_model import User

# Flask app
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///chalenger.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
#from model.user_model import User

# Api app
api = Api(app)
with app.app_context():
    db.create_all()
    user = User(username="******", email="*****@*****.**")
    session = db.session
    session.add(user)
    print User.query.all()
# add route
api.add_resource(Challenges, '/challenges/')
api.add_resource(Challenge, '/challenges/<int:challenge_id>/')
api.add_resource(Days, '/challenges/<int:challenge_id>/days/')

# main
if __name__ == '__main__':
    app.run(debug=True)
 def register(email, first_name, last_name, password):
     return User.register(email, first_name, last_name, password)
Exemple #16
0
def seed():
    from faker import Faker

    fake = Faker()
    for x in range(3):
        User.seed(fake)
Exemple #17
0
 def post(self):
     args = parser.parse_args()
     return post_helper(User.find_by_name(args.username), User,
                        args.username, args, "User")
Exemple #18
0
def authenticate(username, password):
    auth_user = User.find_by_name(username)
    if auth_user and safe_str_cmp(auth_user.password.encode('utf-8'), password.encode('utf-8')):
        return auth_user
Exemple #19
0
def identity(payload):
    user_id = payload['user_name']
    return User.find_by_name(user_id)