コード例 #1
0
    def register(self):
        if request.method == 'POST':
            # pyrebase functionality for register
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")

            user = auth.create_user_with_email_and_password(
                request.json['email'], request.json['password'])

            # Unique User ID
            user_profile = {'name': request.json['name']}
            user_id = str(
                auth.get_account_info(user['idToken'])['users'][0]['localId'])
            connection = [{
                'user_id_sender': 0,
                'user_id_receiver': 0,
                'status': 0
            }]
            userobj = User()
            userobj.setvalues(request.json['email'],
                              user_id,
                              request.json['name'],
                              last_login=current_time,
                              user_profile=user_profile,
                              connection=connection)
            print(userobj.__dict__)

            # Puttting into Realtime DB
            if (user):
                print(user_id)
                database.child("users").child(user_id).update(userobj.__dict__)
                return jsonify(userobj.__dict__)
            else:
                return jsonify({'msg': 'Register Unsuccessfull'})
        return "Login Screen"
コード例 #2
0
ファイル: userViews.py プロジェクト: Rukshani/Euler
def new_user():
    username=request.json.get('username')
    password=request.json.get('password')
    if username is None or password is None:
        abort(400) # missing arguments
    if session.query(User).filter_by(username=username).first() is not None:
        abort(400)# existing user
    user=User(username=username)
    user.hash_password(password)
    session.add(user)
    session.commit()
    return jsonify({'username':user.username}),201
コード例 #3
0
ファイル: userActive.py プロジェクト: love3forever/Lovelog
def active(uid):
    if uid:
        user = User.query(bson.objectid.ObjectId(str(uid)))
        if not user or user.is_authenticated:
            return redirect(url_for('index.indexPage'))
        user.update(isauthenticated=True)
        return redirect(url_for('index.indexPage'))
コード例 #4
0
ファイル: dairyView.py プロジェクト: love3forever/Lovelog
def getPosts():
    '''
    this route is provided to get user's posts
    '''
    uid = current_user.userid
    user = User.query(bson.objectid.ObjectId(str(uid)))
    posts = Posts.objects(poster=user)
    return render_template('dairy/index.html', posts=posts)
コード例 #5
0
def getSysinfoIndex():
    uid = current_user.userid
    user = User.getUserbyID(uid)

    if user:
        infos = SysInfo.objects(awaredof__in=[user])
        return render_template('sysinfo/index.html', infos=infos)
    else:
        return render_template('sysinfo/index.html')
コード例 #6
0
ファイル: signup.py プロジェクト: markghsu/udacity-wdev-blog
def error_username(username):
	q = User.all()
	q.filter("username ="******"That's not a valid username."
	elif dup:
		return "That username is taken."
	else:
		return ""
コード例 #7
0
def get_token():
	request_data=request.get_json()
	username=str(request_data['username'])
	password=str(request_data['password'])

	match=User.usernamePasswordMatch(username, password)
	if match:
		expiration_date=datetime.datetime.utcnow() + datetime.timedelta(seconds=100)  
		token=jwt.encode({'exp': expiration_date}, app.config['SECRET_KEY'], algorithm='HS256')
		return token
	else:
		return Response('',401, mimetype='application/json') #401 UNAUTHORIZED
コード例 #8
0
ファイル: signup.py プロジェクト: markghsu/udacity-wdev-blog
	def post(self):
		username = self.request.get('username')
		password = self.request.get('password')
		verify = self.request.get('verify')
		email = self.request.get('email')
		ue = error_username(username)
		pe = error_password(password)
		ve = "Your passwords didn't match." if password!=verify else ""
		ee = error_email(email)

		if not (ue or pe or ve or ee):
			userhash = make_user_hash(username)
			passhash = make_pw_hash(username,password)
			muser = User(username=username,pwhash=passhash)
			muser.put()
			
			#add to DB and set login cookie
			self.response.headers.add_header('Set-Cookie', str('user_id=%s; Path=/'% userhash))
			self.redirect("/blog/welcome")
		else:
			self.render("signup.html",username=username,uerror=ue,perror=pe,verror=ve,email=email,eerror=ee)
コード例 #9
0
ファイル: userList.py プロジェクト: walgomezb/flaskmvc
    def retriveInfo(self):
        usuarios = [{
            "name": "Juan",
            "lastName": "Perez"
        }, {
            "name": "Pedro",
            "lastName": "Ramirez"
        }]

        for usuario in usuarios:
            newUser = User(usuario['name'], usuario['lastName'])
            self.listOfUser.append(newUser)
コード例 #10
0
ファイル: dairyView.py プロジェクト: love3forever/Lovelog
def uploadFile(form=None, dbModel=None):
    form = form
    if form.validate_on_submit():
        file = request.files['data']
        uid = current_user.userid
        user = User.query(bson.objectid.ObjectId(str(uid)))
        post = dbModel()
        post.poster = user
        post.createdTime = datetime.today()
        post.data.put(form.data.data)
        post.des = form.desc.data
        post.filename = file.filename
        print(form.data.name)
        post.save()
コード例 #11
0
ファイル: generateSyntheticData.py プロジェクト: srnrgn/nutRL
def createUserObject(df):
    """
    From a dataframe, create User objects.
    
    Returns a dict of User objects
    """
    U = {}
    for index, row in df.iterrows():
        user = User(row.nomen, row.sexe_ps, row.v2_age, row.poidsd, row.poidsm,
                    row.bmi, row.menopause, row.regmaig, row.regmedic,
                    row.regrelig, row.regvegr, row.regvegt, row.ordi,
                    row.bonalim, row.agglo9)
        U[row.nomen] = user
    return U
コード例 #12
0
    def login(self):
        if request.method == 'POST':
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")
            print("Current Time =", current_time)
            # pyrebase functionality for login
            user_login = auth.sign_in_with_email_and_password(
                request.json['email'].strip(), request.json['password'])

            users = []
            users = database.child("users").get().val()
            for user in users.values():
                if (user['user_id'] == str(
                        auth.get_account_info(
                            user_login['idToken'])['users'][0]['localId'])):
                    user_login = User()
                    user_login.setvalues(user['email_id'], user['user_id'],
                                         user['name'], current_time,
                                         user['user_profile'],
                                         user['connection'])
                    database.child("users").child(user["user_id"]).update(
                        {'login_status': True})
                    user_login.login_status = True
                    return jsonify(user_login.__dict__)
コード例 #13
0
ファイル: dairyView.py プロジェクト: love3forever/Lovelog
def getFile(filename):
    if filename:
        print(filename)
        uid = current_user.userid
        user = User.query(bson.objectid.ObjectId(str(uid)))
        post = Posts.objects(poster=user, filename=filename).first()
        if post:
            data = post.data
            response = make_response(data.read())
            response.headers[
                "Content-Disposition"] = "attachment; filename={}".format(
                    post.filename)
            return response
    else:
        abort(404)
コード例 #14
0
ファイル: userLogin.py プロジェクト: love3forever/Lovelog
def userLogin():
    if current_user.is_authenticated:
        next = request.args.get('next')
        if next:
            return redirect(next)
    else:
        if current_user.is_active:
            return current_user.userid
        else:
            form = LoginForm()
            if form.validate_on_submit():
                user = User.objects(username=form.username.data).first()
                if user is not None and user.verify_password(form.password.data):
                    login_user(user, form.rememberme.data)
                    return redirect(url_for('index.indexPage'))
                flash('Invalid username or password.')
            return render_template('login/login.html', form=form)
コード例 #15
0
ファイル: instanceMsg.py プロジェクト: love3forever/Lovelog
def index(username):
    if username:
        user = User.objects(username=username).first()
        pair = Pair.query(user.userid).first()
        uid = pair.uid
        print(uid)
        try:
            # if not socketio.server:
            #     return render_template('message/msgIndex.html')
            # if socketio.server.namespace_handlers.has_key('/{}'.format(uid)):
            #     print('room has created')
            # else:
            #     socketio.on_namespace(MessageRoom('/{}'.format(uid)))
            #     print('new room created')
            return render_template('message/chatroom.html', roomid=uid)
        except Exception as e:
            print(str(e))
            return 'somethin wrong'
コード例 #16
0
ファイル: login.py プロジェクト: markghsu/udacity-wdev-blog
	def post(self):
		username = self.request.get('username')
		password = self.request.get('password')
		
		if not username:
			self.render("login.html",error="Please enter a username")
		else:
			q = User.all()
			q.filter("username ="******"login.html",username=username,error="incorrect username or password")
			elif valid_pw(username,password,muser.pwhash):
				userhash = make_user_hash(username)
				self.response.headers.add_header('Set-Cookie', str('user_id=%s; Path=/'% userhash))
				self.redirect("/blog/welcome")
			else:
				self.render("login.html",username=username,error="incorrect username or password")
コード例 #17
0
 def test_delUser(self):
     response = User.deleteUser(userTest.username)
     self.assertEqual(response, 200)
コード例 #18
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from dbModels import Item, Category, Base
from userModel import User

user_engine = create_engine('sqlite:///users.db')
app_engine = create_engine('sqlite:///sportCategories.db')

Base.metadata.bind = app_engine
Base.metadata.bind = user_engine
app_DBSession = sessionmaker(bind=app_engine)
user_DBSession = sessionmaker(bind=user_engine)
app_session = app_DBSession()
user_session = user_DBSession()

user = User(id=1, username='******', password_hash='admin')
user_session.add(user)
user_session.commit()
categories = ([
    "Soccer", "BasketBall", "Baseball", "Frisbee", "Snowboarding",
    "Rock Climbing", "Foosball", "Skating", "Hockey"
])
for category in categories:
    cat = Category(name=category)
    app_session.add(cat)
app_session.commit()
コード例 #19
0
from courseModel import db, Course
from userModel import User
from userModel import db as db2

# creating the databse - this file will run only once
db.create_all()

# check the methods for Course Model
Course.add_course(code="CSE115",
                  instructor="John stuart",
                  name="Introduction to programming language")
Course.add_course(code="CSE465",
                  instructor="Andrew ng",
                  name="Introduction toneural network")
print(Course.get_all_courses())
Course.update_course(code="CSE115", instructor="Alvice preisly")
print(Course.get_course(code="CSE115"))

# creating the databse for user
db2.create_all()
# create dummy user
User.create_user(username="******", password="******")
print(User.get_all_users())
コード例 #20
0
ファイル: userLogin.py プロジェクト: love3forever/Lovelog
def userRegist():
    if current_user.is_authenticated:
        flash('Please logout before registe a new account')
        next = request.args.get('next')
        if next:
            return redirect(next)
        return redirect(url_for('index.indexPage'))
    else:
        form = RegisterForm()
        if form.validate_on_submit():
            user = User()
            user.username = form.username.data
            user.email = form.email.data
            user.password = generate_password_hash(form.password.data)
            user.sex = form.sex.data
            user.age = form.age.data
            user.school = form.school.data
            user.location = form.location.data
            user.createdTime = date.today()
            user.isactive = True
            user.isauthenticated = False

            print(user.username)
            user.save()

            login_user(user)
            return redirect(url_for('index.indexPage'))
        return render_template('login/registe.html', form=form)
コード例 #21
0
 def principle_case_manager(self):
     return User.get_user_with_role(UserCaseRoles.PRINCIPLE_CASE_MANAGER, case_id=self.id)
コード例 #22
0
 def requester(self):
     return User.get_user_with_role(UserCaseRoles.REQUESTER, case_id=self.id)
コード例 #23
0
 def principle_case_manager(self):
     return User.get_user_with_role(UserCaseRoles.PRINCIPLE_CASE_MANAGER,
                                    case_id=self.id)
コード例 #24
0
 def principle_QA(self):
     return User.get_user_with_role(UserTaskRoles.PRINCIPLE_QA, task_id=self.id)
コード例 #25
0
 def principle_QA(self):
     return User.get_user_with_role(UserTaskRoles.PRINCIPLE_QA,
                                    task_id=self.id)
コード例 #26
0
 def secondary_QA(self):
     return User.get_user_with_role(UserTaskRoles.SECONDARY_QA,
                                    task_id=self.id)
コード例 #27
0
app.add_url_rule('/create_connection',
                 methods=["GET", "POST"],
                 view_func=Connection().send_request)

app.add_url_rule('/accept_connection',
                 methods=['POST', 'GET'],
                 view_func=Connection().accept_request)

app.add_url_rule('/reject_connection',
                 methods=['POST', 'GET'],
                 view_func=Connection().reject_request)

app.add_url_rule('/get_match_users',
                 methods=['POST', 'GET'],
                 view_func=User().matching)


@app.route('/get_all_users', methods=['POST', 'GET'])
def get_users():
    users = []
    users = database.child("users").get().val()
    return jsonify(users)


@app.route('/get_all_friends', methods=['POST', 'GET'])
def get_friends():
    users = []
    users = database.child("users").get().val()
    for user in users.values():
        if (user["user_id"] == request.json["user_id"]):
コード例 #28
0
 def principle_investigator(self):
     return User.get_user_with_role(UserTaskRoles.PRINCIPLE_INVESTIGATOR,
                                    task_id=self.id)
コード例 #29
0
ファイル: userLogin.py プロジェクト: love3forever/Lovelog
def userRegistWithCode(code):
    '''
    用户注册,有无邀请码来区分不同的组册情况
    '''
    if current_user.is_authenticated:
        flash('Please logout before registe a new account')
        next = request.args.get('next')
        if next:
            return redirect(next)
        return redirect(url_for('index.indexPage'))
    else:
        form = RegisterForm()
        if code:
            form.inviteCode.data = code
        if form.validate_on_submit():
            user = User()
            user.username = form.username.data
            user.email = form.email.data
            user.password = generate_password_hash(form.password.data)
            user.sex = form.sex.data
            user.age = form.age.data
            user.school = form.school.data
            user.location = form.location.data
            user.createdTime = date.today()
            user.isactive = True
            user.isauthenticated = False
            uniqueCode = form.inviteCode.data
            if uniqueCode:
                if Pair.query(bson.objectid.ObjectId(str(code))):
                    flash('This invite code has been used')
                    return redirect(url_for('login.userRegist'))
                user.save()
                login_user(user)
                if user.sex == 'male':
                    try:
                        pair = Pair()
                        pair.boy = user
                        pair.girl = User.query(
                            bson.objectid.ObjectId(str(code)))
                        pair.save()
                    except Exception as e:
                        print(str(e))
                else:
                    try:
                        pair = Pair()
                        pair.girl = user
                        pair.boy = User.query(
                            bson.objectid.ObjectId(str(code)))
                        pair.save()
                    except Exception as e:
                        print(str(e))
                return redirect(url_for('index.indexPage'))
            print(user.username)
            user.save()
            login_user(user)
            return redirect(url_for('index.indexPage'))
        return render_template('login/registe.html', form=form)
コード例 #30
0
 def principle_investigator(self):
     return User.get_user_with_role(UserTaskRoles.PRINCIPLE_INVESTIGATOR, task_id=self.id)
コード例 #31
0
 def secondary_case_manager(self):
     return User.get_user_with_role(UserCaseRoles.SECONDARY_CASE_MANAGER,
                                    case_id=self.id)
コード例 #32
0
 def secondary_investigator(self):
     return User.get_user_with_role(UserTaskRoles.SECONDARY_INVESTIGATOR, task_id=self.id)
コード例 #33
0
 def requester(self):
     return User.get_user_with_role(UserCaseRoles.REQUESTER,
                                    case_id=self.id)
コード例 #34
0
 def secondary_QA(self):
     return User.get_user_with_role(UserTaskRoles.SECONDARY_QA, task_id=self.id)
コード例 #35
0
 def testMatchUsernamePassword(self):
     response = User.username_password_match('admin', '12345')
     self.assertEqual(response, True)
コード例 #36
0
 def secondary_case_manager(self):
     return User.get_user_with_role(UserCaseRoles.SECONDARY_CASE_MANAGER, case_id=self.id)
コード例 #37
0
 def test_createUser(self):
     userTest.username = userTest.randomString()
     response = User.createUser(userTest.username, userTest.randomString(), 1)
     self.assertEqual(response, 200)
コード例 #38
0
 def load_user(uid):
     return User.query(bson.objectid.ObjectId(str(uid)))
コード例 #39
0
 def test_getRolePerUser(self):
     response = User.getRole(userTest.username)
     self.assertEqual(response, 'admin')
コード例 #40
0
 def secondary_investigator(self):
     return User.get_user_with_role(UserTaskRoles.SECONDARY_INVESTIGATOR,
                                    task_id=self.id)
コード例 #41
0
def getInfoStatus():
    uid = current_user.userid
    user = User.getUserbyID(uid)

    infos = SysInfo.objects(awaredof__in=[user])
    return jsonify({'count': len(infos)})