示例#1
0
文件: wsgi.py 项目: srihi/achat
def initialize_application(app):
    # create the directory for the database if it does not exist. This might happen if the app is being run for the
    # first time.
    if not os.path.exists(DB_DIRECTORY):
        logger.info('Database directory does not exist. Creating...')
        os.makedirs(DB_DIRECTORY)

    # create and initialize the database if it does not exist.
    if not os.path.isfile(app.config['SQLALCHEMY_DATABASE_URI']):
        logger.info("Data base file is missing {}".format(
            app.config['SQLALCHEMY_DATABASE_URI']))
        initialize_database(app)

    # check if there are any uses in the system. If there are none create at least one admin user to be able to access
    # the system.
    with app.app_context():
        users = UserAccount.query.all()
        if not users:
            logger.info(
                'There are no users in the database. Creating an admin user account with default settings.'
            )
            new_user_guid = generate_hash_key()
            admin_user = UserAccount('*****@*****.**', 'Up@8dHgd',
                                     new_user_guid, False, datetime.now())
            db.session.add(admin_user)
            db.session.commit()
示例#2
0
    async def create_new_user(
            self,
            super_acc: Optional[SuperAccount] = None
    ) -> Tuple[UserAccount, str]:
        if super_acc is None:
            super_acc = await self.create_new_super_account()

        new_acc = UserAccount()

        password = generate_password()
        salt, hashed = hash_password(password)
        new_acc.salt = salt
        new_acc.pword = hashed
        new_acc.super_id = super_acc.super_id
        new_acc.login = generate_uuid4()

        # handle a minuscule chance that the login already exists in the
        # database
        count_user = ("select count(*) "
                      "from user_account u "
                      "where u.login = :login ")
        while (await self.fetch_one(count_user,
                                    login=new_acc.login))['count'] > 0:
            new_acc.login = generate_uuid4()

        query = ("insert into user_account (login, salt, pword, super_id)"
                 "values (:login, :salt, :pword, :super_id)")

        await self.execute(query,
                           login=new_acc.login,
                           salt=new_acc.salt,
                           pword=new_acc.pword,
                           super_id=new_acc.super_id)
        return new_acc, password
示例#3
0
def add_user(username, email, password):
    #t_bf = int(time.time() * 1000)
    pw_salt = uuid.uuid4().hex
    salted_pw = password + pw_salt
    #t_af = int(time.time() * 1000)
    #sys.stderr.write("Salting takes: %d\n" % (t_af - t_bf))
    hashed_pw = hashlib.sha512(salted_pw.encode('utf-8')).hexdigest()
    try:
        #t_bf = int(time.time() * 1000)
        # Add a user.
        user = UserAccount(username=username,
                           email=email,
                           password=hashed_pw,
                           password_salt=pw_salt)
        #t_af = int(time.time() * 1000)
        #sys.stderr.write("User Object Creation takes: %d\n" % (t_af - t_bf))
        #t_bf = int(time.time() * 1000)
        session.add(user)
        #t_af = int(time.time() * 1000)
        #sys.stderr.write("Adding User to Session takes: %d\n" % (t_af - t_bf))

        # Add its activation token
        #t_bf = int(time.time() * 1000)
        ac_token = toekn_gen()
        #t_af = int(time.time() * 1000)
        #sys.stderr.write("Token Generation takes: %d\n" % (t_af - t_bf))
        #t_bf = int(time.time() * 1000)
        user_ac_token = UserActivationToken(user_account=user,
                                            activation_token=ac_token)
        #t_af = int(time.time() * 1000)
        #sys.stderr.write("Token Object Creation takes: %d\n" % (t_af - t_bf))
        #t_bf = int(time.time() * 1000)
        session.add(user_ac_token)
        #t_af = int(time.time() * 1000)
        #t_bf = int(time.time() * 1000)
        #sys.stderr.write("Adding User Token to Session takes: %d\n" % (t_af - t_bf))
        #t_bf = int(time.time() * 1000)
        session.commit()
        #t_af = int(time.time() * 1000)
        #sys.stderr.write("Session Commit takes: %d\n" % (t_af - t_bf))

        #t_bf = int(time.time() * 1000)
        # Async sending emails.
        send_user_token(email, ac_token)
        #t_af = int(time.time() * 1000)
        #sys.stderr.write("AMQP Transfer takes: %d\n" % (t_af - t_bf))
        return generate_message(STATUS_OK, SUCCESS_ACCOUNT_CREATED_MESSAGE)
    except IntegrityError as err:
        session.rollback()
        print(err)
        if err.orig.args[0].startswith(ERROR_ACCOUNT_EXISTED_CODE):
            return generate_message(STATUS_ERROR,
                                    ERROR_ACCOUNT_EXISTED_MESSAGE)
        return generate_message(STATUS_ERROR, ERROR_UNKNOWN_MESSAGE)
    except Exception as err:
        print(err)
        return generate_message(STATUS_ERROR, ERROR_UNKNOWN_MESSAGE)
示例#4
0
 async def get_user(self, login: str) -> Optional[UserAccount]:
     """ Get user with specified UUID. Just send str representation of UUID """
     query = ("select u.login, u.salt, u.pword, u.super_id "
              "from user_account u "
              "where u.login = :login")
     result = await self.fetch_one(query=query, login=login)
     if result is None:
         return None
     else:
         return UserAccount(**result)
示例#5
0
 async def users_online_in_thread(self,
                                  thread_id: int) -> Iterable[UserAccount]:
     # TODO: thread_id is unused because all users connected to the server
     # can view all threads hence they are all online
     query = (
         "select u.login, u.salt, u.pword, u.super_id, u.last_request_time "
         "from user_account u "
         "where u.last_request_time > now() - (1 * interval '1 minute')")
     online = await self.fetch_all(query=query)
     return map(lambda u: UserAccount(**u), online)
示例#6
0
def regist(email, password):
    if check(email):
        raise DuplicateException(u"注册邮箱地址重复")
    ul = UserLogin(email, password)
    g.db.add(ul)
    g.db.flush()
    up = UserProfile(ul)
    uc = UserAccount(ul)
    g.db.add(up)
    g.db.add(uc)
    g.db.flush()
    g.db.commit()
    return ul.id
示例#7
0
def create_user(request):
    if request.method == "POST":
        body = json.loads(request.body)
        registered_usr = User.objects.filter(username=body['username'])
        if len(registered_usr) > 0:
            return HttpResponseForbidden("User already exists")
        else:
            user = User.objects.create_user(body['username'], body['email'], body['password'], is_active=False)
            user.save()
            user_acc = UserAccount(name=body['username'])
            user_acc.save()
            return JsonResponse({'state': 'ok'})
    else:
        return JsonResponse({'state': 'error', 'reason': 'incorrect request method'})
示例#8
0
def add_client_account():
    if request.data:
        content = request.json
        debtor_name = content['debtor_name']
        debtor_phone_number = content['debtor_phone_number']
        amount = content['amount']
        user_id = content['user_id']
        try:
            user_account = UserAccount(debtor_name=debtor_name,
                                       debtor_phone_number=debtor_phone_number,
                                       amount=amount,
                                       user_id=user_id)
            db.session.add(user_account)
            db.session.commit()
            return jsonify(user_account.serialize()), 201
        except Exception as e:
            return jsonify({"Error": str(e)}), 401
def get_logged_user():
    try:
        token = get_token_auth_header()
        payload = verify_decode_jwt(token)
        oauth_id = payload['sub']
        # TODO: search user. If not found add it to DB
        user = User.query.filter(
            User.oauth_accounts.any(UserAccount.oauth_id == oauth_id)).first()
        if not user:
            user = User(name=oauth_id)
            user.insert()
            user_account = UserAccount(user_id=user.id, oauth_id=oauth_id)
            user_account.insert()
        return user
    except AuthError as ex:
        print(ex)
        return None
示例#10
0
    def post(self):

        register_args = {
            'userName': fields.Str(required=True),
            'password': fields.Str(required=True),
            'firstName': fields.Str(required=False),
            'lastName': fields.Str(required=False)
        }

        request_args = parser.parse(register_args, request)

        userEmail = request_args['userName']
        password = request_args['password']
        firstName = request_args['firstName']
        lastName = request_args['lastName']

        # check if the users already exists
        user = UserAccount.query.filter_by(user_email=userEmail).first()
        if user:
            logger.error("User with email {} already exists. Registration failed.".format(userEmail))
            return jsonify(authToken="",
                           isRegistrationSuccessful=False,
                           registrationErrorMessage="User with email {} already exists. Registration failed.".format(
                               userEmail))
        else:
            authToken = generate_hash_key()

            new_user_guid = generate_hash_key()
            user_account = UserAccount(userEmail, password, new_user_guid, False, datetime.now())
            user_profile = UserProfile(new_user_guid, firstName, lastName)
            user_auth_token = AuthTokens(new_user_guid, authToken, -1)

            db.session.add(user_account)
            db.session.add(user_profile)
            db.session.add(user_auth_token)

            db.session.commit()

            logger.info("New user registered with email {}.".format(userEmail))

            return jsonify(authToken=authToken,
                           isRegistrationSuccessful=True,
                           registrationErrorMessage="")
from models import Users, UserAccount

user_account = UserAccount()


def register(username, password):
    user = Users(username, password)
    user_account.signup(user)
    print('Successfully registerered!')


def login(username, password):
    for account in user_account.accounts:
        if password == account['password'] and username == account['username']:
            return 'You are now logged In!'
    return "Sorry account does not exist, register if you don't have an account yet."


def menu():
    choice = input("""
  1.) r - register
  2.) l - login
  3.) d - display user account data
  4.) cp - forgot/change password?
  5.) s - save user account data
  6.) c - check total count of users
  7.) q - quit
  """)
    while choice != 'q':
        if choice == 'r':
            username1 = input('Enter Username: ')