Esempio n. 1
0
def profile(username):
    """ profile handler """
    _user = user.User(graph=graph, username=username)
    curuser = _user.find()
    email = curuser['email']

    all_languages = queries.get_all_languages(graph, email)
    languages = queries.get_users_languages(graph, email)
    projects = queries.get_users_projects(graph, email)

    similar = []
    similar_lang = []
    common = []

    viewer_email = session.get('email')
    if viewer_email:
        viewer = user.User(graph=graph, email=viewer_email)
        if viewer.email == email:
            similar = viewer.get_similar_users()
            similar_lang = viewer.get_similar_users_lang()
        else:
            common = viewer.get_commonality_of_user(email)

    return render_template(
        'profile.html',
        email=email,
        username=curuser['username'],
        languages=languages,
        all_languages=all_languages,
        projects=projects,
        similar=similar,
        similar_lang=similar_lang,
        common=common
    )
Esempio n. 2
0
def reg():

    result = {}
    if request.method == 'POST':
        args = request.form.to_dict()
        if request.form.get('reg', None) == '发送验证码':
            verification = random.randint(100000, 999999)
            d = {}
            d['en_phone'] = args['phone']  #这里必须字典传参,改User里的话太麻烦
            u = user.User(**d)
            if not u.phone_legal():
                result = {'code': 61, 'message': '手机号不合法!'}
            elif u.check_exist(args['phone']):
                result = {'code': 59, 'message': '手机号已经存在,请直接登录!'}
            else:
                m = message.Message(args['phone'], verification)
                send_result = m.send()
                if send_result['code'] == 0:
                    result = {'code': 60, 'message': '验证码已经发送!'}
                    session['verification'] = verification
                    session['reg_phone'] = args['phone']
                else:
                    result = {'code': 62, 'message': '验证码发送失败!'}
            return render_template('reg.html',
                                   result=result,
                                   verification=verification)
        elif request.form.get('reg', None) == '注册':
            if (len(args['phone']) == 0 or len(args['passwd']) == 0
                    or len(args['confirm_passwd']) == 0
                    or len(args['class_type']) == 0
                    or len(args['class_num']) == 0 or len(args['sex']) == 0
                    or len(args['verification']) == 0):
                result = {'code': 51, 'message': '接受到的注册信息不完整!'}
            elif not session:
                result = {'code': 63, 'message': '请进行手机验证!'}
            elif session['reg_phone'] != args['phone']:
                result = {'code': 59, 'message': '请用接收到验证码的手机注册!'}
            elif args['confirm_passwd'] != args['passwd']:
                result['code'] = 57
                result['message'] = '密码不一致'
            elif int(args['verification']) != int(
                    session['verification']):  #需要注意session的类型和args的类型
                result = {'code': 58, 'message': '验证码错误!'}
            else:
                reg_info = {
                    'en_phone': args['phone'],
                    'en_passwd': args['passwd'],
                    'class_type': args['class_type'],
                    'class_num': args['class_num'],
                    'sex': args['sex']
                }
                r = user.User(**reg_info)
                result = r.reg()
            return render_template('reg.html', result=result)
        else:
            return '<h1>这是什么请求,你作弊!</h1>'
    else:
        return render_template('reg.html', result=result)
Esempio n. 3
0
async def set_ssh_command(req: Request,
                          background_tasks: BackgroundTasks,
                          db: Session = Depends(get_db)):
    if not await is_request_valid(req):
        raise HTTPException(400, detail='invalid token')
    r_from = await req.form()
    if not await openstack_controller.validate_ssh(r_from['text']):
        return {
            'response_type': 'in_thread',
            'type': 'mrkdwn',
            'text': f'Error: invalid ssh-key: `{r_from["text"]}`.'
        }

    db_usr = await user_controller.get_user(db=db, id=r_from['user_id'])
    usr = await user_controller.db_user2user(usr=db_usr)
    if usr == None:
        #create user
        usr = user.User(id=r_from['user_id'], nick=r_from['user_name'])
        db_usr = await user_controller.create_user(db=db, usr=usr)

    background_tasks.add_task(set_ssh_key, r_from=r_from, usr=usr, db=db)
    return {
        'response_type': 'in_thread',
        'type': 'mrkdwn',
        'text': 'Start working:-)'
    }
Esempio n. 4
0
 async def post(self, request, technical):
     try:
         data = request.json
         logins = [
             x['login'] for x in await user.User.list_users(
                 redis_conn=request.app.redis)
         ]
         if data['login'] not in logins:
             data['created_at'] = datetime.now().strftime(
                 "%Y-%m-%d %H:%M:%S")
             with await request.app.redis as redis:
                 curr_merchant = merchant.Merchant(id=data['merchant_id'],
                                                   redis_conn=redis)
                 curr_merchant_id, result = await curr_merchant.get_merchant(
                 )
                 if curr_merchant_id is not None:
                     new_user = user.User(redis_conn=redis)
                     data['user_id'], data[
                         'token'] = await new_user.create_user(data=data)
                     return json(data, status=201)
                 else:
                     return json({"message": "There is no such merchant."},
                                 status=400)
         else:
             return json(
                 {
                     "message":
                     "User with the login {0} already exists.".format(
                         data['login'])
                 },
                 status=409)
     except Exception:
         capture_exception(data=request.json)
         return json({"message": "Internal Server error"}, status=500)
Esempio n. 5
0
def save_latest_profile(access_params, profile_map):
    logging.debug("Saving latest profile for email=%s", profile_map['email'])
    matched_users = user.User.objects(email_address=profile_map['email'])
    logging.debug("Found %d matched users", len(matched_users))

    new_user = False
    user_instance = None

    if len(matched_users) > 1:
        logging.error("ERROR! We found more than one matching user for email=%s", profile_map['email'])
        raise Exception('More than one user found for email' + profile_map['email'])

    if len(matched_users) == 0:
        logging.info("NEW USER!")
        new_user = True
        user_instance = user.User()
        user_instance.external_account_type = user.ACCOUNT_TYPE['AWS']
        user_instance.external_account_id = profile_map['user_id']
    else:
        user_instance = matched_users[0]

    user_instance.access_token = access_params['access_token']
    user_instance.email_address = profile_map['email']
    user_instance.refresh_token = access_params['refresh_token']
    user_instance.profile_name = profile_map['name']

    current_epoch = pendulum.now().int_timestamp
    expiry_epoch = current_epoch + app.app.config['SESSION_EXPIRES_IN']#int(access_params['expires_in'])
    user_instance.token_expires_epoch = expiry_epoch

    logging.debug("current_epoch=%d, expiry_epoch=%d", current_epoch, expiry_epoch)

    user_instance.save()

    return new_user, user_instance
Esempio n. 6
0
    def FacebookLogin(self):
        verification_code = self.request.get('code')
        args = dict(client_id=properties.FACEBOOK_APP_ID, redirect_uri=self.request.path_url)
        if verification_code:
            
            args["client_secret"] = properties.FACEBOOK_APP_SECRET
            args["code"] = verification_code
            
            req = urllib2.Request(properties.FACEBOOK_URL + properties.FACEBOOK_OAUTH_URL, urllib.urlencode(args))
            response = urllib2.urlopen(req)
            tokens = urlparse.parse_qs(response.read())

            #stores session
            self.session['facebook-token'] = self.context['token'] = tokens['access_token'][0]
            
            #saves FB profile
            self.context['profile'] = json.load(urllib.urlopen(properties.FACEBOOK_URL + "/me?" + urllib.urlencode(dict(access_token=self.context['token']))))
            
            #adds user
            current = user.User(key_name=str(self.context['profile']["id"]), id=str(self.context['profile']["id"]),
                name=self.context['profile']["name"], access_token=self.context['token'],
                profile_url=self.context['profile']["link"])
            current.put()

            self.redirect('/')
        else:
            self.redirect(properties.FACEBOOK_URL + properties.FACEBOOK_OAUTH_AUTHORISE + urllib.urlencode(args))
Esempio n. 7
0
    def __init__(self):
        self.currentUser = user.User(None)
        self.trailPoints = collections.deque()
        self.currentPage = constants.Page.HOME
        self.direction = constants.Direction.NONE
        self.lastSwipe = 0  # the last time
        self.userList = []  # all the user objects saved in the system
        self.alphabetIndex = 0  # index of the alphabet user is currently on for the name screen
        self.selectedMonth = datetime.date.today(
        ).month  # the current month the user is looking at on the habits screen
        self.active = True  # whether the system is on or not
        self.gameStart = 0  # what time the game started at
        self.lastGermCheck = 0  # the last time the game checked to generate a germ
        self.germList = []  # the germs currently active for the game
        self.gameScore = 0

        # the order in which the 4 quadrants are gone through for a game
        self.quadrantOrder = [
            constants.Quadrant.TOPRIGHT, constants.Quadrant.TOPLEFT,
            constants.Quadrant.BOTTOMLEFT, constants.Quadrant.BOTTOMRIGHT
        ]
        self.curId = 0  # the id in the quadrant order the game is currently on
        self.currentQuadrant = 0  # the current quadrant the game is on
        self.lastQuadrantTransition = 0  # the last time
        self.canvas = self.makeCanvas()  # the canvas everything is drawn on
        self.faceTracking = False  # whether or not the system is performing facial recognition
        self.selectedUser = 0  # which user (as an index) the user has currently selected on the enterUser screen
        self.newHighScore = False  # whether or not the user got a new high score on their last game
Esempio n. 8
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username')
        parser.add_argument('name')
        parser.add_argument('email')
        #parser.add_argument('role')
        parser.add_argument('cellphone')
        parser.add_argument('street')
        parser.add_argument('neighborhood')
        parser.add_argument('number')
        parser.add_argument('city')
        parser.add_argument('state')
        args = parser.parse_args()

        new_user = user.User(username=args['username'],
                             name=args['name'],
                             email=args['email'],
                             cellphone=args['cellphone'])
        new_address = address.Address(street=args['street'],
                                      neighborhood=args['neighborhood'],
                                      number=args['number'],
                                      city=args['city'],
                                      state=args['state'],
                                      user=new_user)

        db.session.add(new_user)
        db.session.commit()

        return {
            new_user.id: {
                'name': new_user.name,
                'email': new_user.email
            }
        }, 201
Esempio n. 9
0
File: db.py Progetto: Skylore/shop
    def sign_up(self, name: str, login: str, password: str) -> user.User:
        if login in self.users:
            raise AssertionError

        u = user.User(name, login, password, 'customer')
        self.users[login] = u

        return u
Esempio n. 10
0
    def insert_user(self, name, user_hash, email, birthdate):
        result = self.find_one({"email": email})
        if result is not None:
            return [False]

        new_user = user.User(name, user_hash, email, birthdate)
        self.insert_one(new_user.json())
        return [True, new_user.uuid]
Esempio n. 11
0
def create_user(db: Session, users: user_schema.UserCreate):
    db_user = user.User(user_name=users.user_name,
                        role=users.role,
                        activate=True)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
Esempio n. 12
0
def login():
    """ login handler """
    error = None
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        if not user.User(graph=graph, email=email).verify_password(password):
            if not user.User(graph=graph, username=email).verify_password(password):
                error = 'Invalid login.'
        if error ==  None:
            _user = user.User(graph=graph, email=email).find()
            if _user == None:
                _user = user.User(graph=graph, username=email).find()
            session['email'] = email
            session['username'] = _user['username']
            return redirect(url_for('index'))
    return render_template('login.html', error=error)
Esempio n. 13
0
def like_project(project_id):
    """ like project handler """
    email = session.get('email')
    username = session.get('username')
    if not username:
        abort(400, 'You must be logged in to like a project.')
    user.User(graph, email).like_project(project_id)
    return redirect(request.referrer)
Esempio n. 14
0
def create_new_user(db: Session, user_name: str, role: str):
    db_user = user.User(id=get_random_string(8),
                        user_name=user_name,
                        role=role,
                        activate="1")
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
Esempio n. 15
0
def getUser(state):
    directory = os.path.dirname(os.path.abspath(__file__)) + "/users"
    userFiles = next(os.walk(directory))[2]  # list of user files
    userList = []
    loadedEncodings = []

    for userFile in userFiles:
        file = open("users/" + userFile, 'rb')
        loadedUser = pickle.load(file)
        file.close()

        userList.append(loadedUser)
        loadedImage = loadedUser.image
        loadedEncodings.append(face_recognition.face_encodings(loadedImage)[0])

    onScreenFaces = []
    onScreenEncodings = []
    processing = True

    camera = PiCamera()
    camera.resolution = (800, 800)
    camera.framerate = 32
    rawCapture = PiRGBArray(camera, size=(800, 800))
    time.sleep(0.1)
    state.faceTracking = True
    for image in camera.capture_continuous(rawCapture,
                                           format="bgr",
                                           use_video_port=True):
        frame = image.array
        frame = cv2.flip(
            frame, 0)  # flips along x-axis due to how our camera is positioned

        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

        # only process every other frame of video to save time
        if processing:
            onScreenFaces = face_recognition.face_locations(small_frame)
            onScreenEncodings = face_recognition.face_encodings(
                small_frame, onScreenFaces)

            if len(onScreenFaces) != 0:
                for encoding in onScreenEncodings:
                    match = face_recognition.compare_faces(
                        loadedEncodings, encoding)

                    for id in range(len(loadedEncodings)):
                        if match[id].any(
                        ):  # if any of the faces on screen match the loaded user's
                            camera.close()
                            return userList[id], userList, False
                camera.close()
                newUser = user.User(
                    frame)  # only reached if face on screen was not recognized
                return newUser, userList, True
        processing = not processing
        rawCapture.truncate(0)
Esempio n. 16
0
def login():
    resp = flask.request.json
    the_user = user.User.query.filter(user.User.fb_id == resp['id']).first()
    if not the_user:
        the_user = user.User()
        the_user.fb_id = resp['id']
        the_user.name = resp['name']
        db.session.add(the_user)
        db.session.commit()
    return json.dumps(the_user.as_dict())
Esempio n. 17
0
def add():
    # username = '******'
    # pwd = hashlib.md5('123456'.encode('utf-8')).hexdigest()
    u = user.User()
    u.username = '******'
    u.email = '*****@*****.**'
    db.session.add(u)
    session['user'] = u
    db.session.commit()
    return Response('添加成功')
Esempio n. 18
0
def displayLogin():
    username = input('Username: '******'Password: '******'msg'])
    _uAuth.storeTokens(t_type='access', token=r.body['access_token'])
    return _pageLogged.menu()
Esempio n. 19
0
 async def delete(self, request, id, technical):
     try:
         with await request.app.redis as redis:
             curr_user = user.User(id=id, redis_conn=redis)
             await curr_user.delete_user()
         return json({"message": "There is no such user anymore."},
                     status=204)
     except Exception:
         capture_exception()
         return json({"message": "Internal Server error"}, status=500)
Esempio n. 20
0
 def test_verify_attr(self):
     ''' check for attributes '''
     obj = user.User()
     self.assertTrue(hasattr(obj, 'email'))
     self.assertTrue(hasattr(obj, 'password'))
     self.assertTrue(hasattr(obj, 'first_name'))
     self.assertTrue(hasattr(obj, 'last_name'))
     self.assertTrue(hasattr(obj, 'id'))
     self.assertTrue(hasattr(obj, 'created_at'))
     self.assertTrue(hasattr(obj, 'updated_at'))
     self.assertEqual(obj.__class__.__name__, 'User')
Esempio n. 21
0
def get_purchases(client_id):
    u = user.User()
    u.get(client_id)
    p = repo.Purchase()
    p.client_id = client_id
    data = p.get_purchases() if u.u_type == "Client" else p.all()
    arr = []
    for record in data:
        arr.append(repo.client_order_to_json(record))
    result = {"data": arr}
    return make_response(jsonify(result)), 200
Esempio n. 22
0
 def test_typos(self):
     ''' check for attributes '''
     obj = user.User()
     self.assertEqual(type(obj.email), str)
     self.assertEqual(type(obj.password), str)
     self.assertEqual(type(obj.first_name), str)
     self.assertEqual(type(obj.last_name), str)
     self.assertEqual(type(obj.id), str)
     self.assertEqual(type(obj.created_at), datetime)
     self.assertEqual(type(obj.updated_at), datetime)
     self.assertEqual(obj.__class__.__name__, 'User')
Esempio n. 23
0
def login():
    result = {}
    if request.method == 'POST':
        args = request.form.to_dict()
        u = user.User(args['phone'], args['passwd'])
        result = u.login()
        if result['code'] == 0:
            session['phone'] = args['phone']
            return redirect(url_for('index'))

        result = u.login()['message']
    return render_template('login.html', result=result)
Esempio n. 24
0
 def get_all_users(self):
     result = []
     # Get all users and ignore _Id (standard mongodb id)
     #  because object id's can't be parsed to json
     users = self.find_all()
     for l_user in users:
         c_user = user.User()
         c_user.from_mongo(l_user)
         result.append(c_user.json())
     if result is not None:
         return [True, result]
     return [False]
def register():
    """Make the register"""
    from models import user

    if request.method == "POST":
        names = request.form["names"]
        last_names = request.form["lastNames"]
        email = request.form["email"]
        document = request.form['user_dni']
        phone = request.form['phone']
        password = request.form["password"]
        confirmPwd = request.form["confirmPassword"]

        params = [names, last_names, email, document, phone, password, confirmPwd]
        nums = ["0","1", "2", "3", "4", "5", "6", "7", "8", "9"]

        for n in params:

            if len(n) == 0:
                error = True
                return render_template("register.html", error_params=error)

        for verify in [document, phone]:
            for lttr in verify:
                if lttr not in nums:
                    return render_template("register.html", error_chr=True) 
        
        if password != confirmPwd:
            error = True
            return render_template("register.html", error_match=error)

        allUsers = [user.email for user in user.User.query.all()]

        if email in allUsers:
            error = True
            return render_template("register.html", error_exist=error)
        else:
            tipo = 'REG'
            keyGen = '{}'.format(random.randrange(10**6))
            data = { 'name': names, 'last_name': last_names, 'code': keyGen }
            sendMail(tipo, email, data)
            md5Pwd = md5(password.encode('utf-8')).hexdigest()
            #try:
            newUser = user.User(names, last_names, email, document, phone, md5Pwd, keyGen)
            #except:
             #   return render_template("register.html", error_data=True)
            newUser.save()
            session["name"] = names
            session["last_names"] = last_names
            session["emailcheck"] = email
            return redirect(url_for('emailCheck'))
    return render_template("register.html")
Esempio n. 26
0
def create_user():
    """Creates a User object"""
    if not request.json:
        abort(400, 'Not a JSON')
    if 'email' not in request.json:
        abort(400, 'Missing email')
    if 'password' not in request.json:
        abort(400, 'Missing password')
    my_user = user.User(email=request.json.get('email', ""),
                        password=request.json.get('password', ""))
    storage.new(my_user)
    my_user.save()
    return make_response(jsonify(my_user.to_dict()), 201)
Esempio n. 27
0
def open_pickle_jar(picklejar):
    """
    Loads user profile from pickled file
    """
    try:
        input = open(os.path.join(".", "data", "users", picklejar + ".pkl"),
                     'rb')
        my_class = load(input)
        input.close()
    except FileNotFoundError:
        # my_words[defined word] = (numTimesDefined, definition)
        my_class = user.User("", {}, {})
    return my_class
Esempio n. 28
0
def add_user():
    #Need to check password_1 == password_2

    user = u.User(request.json['fname'], request.json['lname'],
                  request.json['email'],
                  generate_password_hash(request.json['password_1']))

    mongoConnect = mongodb.MongoDb()
    db = mongoConnect.getClient().unga
    db.users.insert(user.serialize())
    mongoConnect.getClient().close()

    return jsonify({"user": "******" + user.getUid() + " created"})
Esempio n. 29
0
def create_user(data):
    try:
        new_user = user.User(data["user_name"], data["company"],
                             data["password"])
        db.session.add(new_user)
        db.session.commit()
        return {
            "message":
            f"user {new_user.user_name} has been created successfully."
        }
    except Exception as e:
        print(e)
        return {"message": "Error :"}
Esempio n. 30
0
 async def patch(self, request, id, technical):
     try:
         with await request.app.redis as redis:
             curr_user = user.User(id=id, redis_conn=redis)
             token = await curr_user.refresh()
         if token is not None:
             return json({"user_id": int(id), "token": token}, status=200)
         else:
             return json({"message": "User is not existed yet."},
                         status=404)
     except Exception as e:
         capture_exception(data=request.json)
         return json({"message": "Internal Server error"}, status=500)