예제 #1
0
def setup():
    db.create_all(app=manager.app)
    with manager.app.app_context():
        u = User()
        u.username = '******'
        u.password = '******'
        db.session.add(u)
        db.session.commit()
예제 #2
0
def fake_users(session, request):
    u = User()
    u.username = '******'
    u.password = '******'
    session.add(u)
    session.commit()

    yield u
예제 #3
0
def get_all_user_blogs(user_id=None):

    if user_id is not None:
        user = User.get_by_id(user_id)
    else:
        user = User.get_by_email(session['email'])
    blogs = user.get_blogs()
    return render_template('/user_page/user_blogs.html', blogs=blogs, email=user._email)
예제 #4
0
def create_user():
    name = request.form.get('username', None)
    password = request.form.get('password', None)
    if all([name, password]):
        u = User()
        u.password = password
        u.username = name
        db.session.add(u)
        db.session.commit()
        return 'OK', 200
    return 'Error', 400
예제 #5
0
    def done(self):
        #make sure the user doesn't already exist
        u = User.by_name(self.username)
        if u:
            msg = 'That user already exists.'
            self.render('signup-form.html', error_username = msg)
        else:
            u = User.register(self.username, self.password, self.email)
            u.put()

            self.login(u)
            self.redirect('/')
예제 #6
0
def user_login():

    if request.method == 'GET':
        #return render_template('/login/login.html')
        return login()
    else:
        email  = request.form['email']
        passwd = request.form['password']
        if User.login_valid(email, passwd):
            User.login(email)
            return render_template('/user_page/user_profile_page.html', email=session['email'])
        else:
            session['email'] = None
            return login()
def test_users(session):
    u = User()
    u.username = '******'
    u.password = '******'

    session.add(u)
    session.commit()

    t = session.query(User).filter(User.username == 'test_user').first()

    assert t is not None
    assert u == t
    assert t.password == u.password
    assert t.api_key is None
예제 #8
0
def register_user():

    if request.method == 'GET':
        return render_template('/register/register.html')
    else:
        email  = request.form['email']
        passwd = request.form['password']

        if User.get_by_email(email):
            return 'user already exists'
        else:
            User.register(email, passwd)

    return render_template('/user_page/user_profile_page.html', email=session['email'])
예제 #9
0
def test_polymorphism():
    me = User.create(name="pete")
    Photo.create(user_id=me.user_id, name="sunset")
    Video.create(user_id=me.user_id, name="kickball")

    for content in Video.objects(user_id=me.user_id):
        print content
예제 #10
0
    def post(self):
        """Checks if user already exists, otherwise creates a new User in db"""
        args = post_parser.parse_args()
        user = User(args.email, args.password)

        # Check if already registered
        user_already_exists = User.query.filter(User.email == args.email).first()
        if user_already_exists:
            return {'success': False, 'message': 'That user already exists', 'data': None}

        # Try saving the user to db
        try:
            user.save()
            return {'success': True, 'message': 'User successfully added', 'data': None}
        except ValueError as e:
            return {'success': False, 'message': str(e), 'data': None}
예제 #11
0
def prepareEmailMessagesGenerator():
    # This must be run after buildDailyList
    # Since only there a daily message limit is applied
    # though, this limit can be different for emails
    path_current = os.path.dirname(__file__)
    root_path = os.path.split(path_current)[0]
    view_path = root_path + "/views/daily_email.html"

    today = datetime.date.today()
    emails_dict = {}
    for user in User.all().filter("account_status =", "enabled").\
        filter("use_daily_email =", "yes"):

        parameters = {}
        parameters["dict_row"] = []
        for lli in LearnList.all().\
            filter("next_serve_date =", today).\
            filter("twitter_user ="******" " + lli.dict_entry.pronounce)
            l.append(lli.dict_entry.meaning)
            parameters["dict_row"].append(l)
        emails_dict["email"] = user.email
        emails_dict["message"] = template.\
            render(view_path, parameters)
        yield emails_dict
예제 #12
0
    def get_friends_list(self, user):
        twitterApi = Twitter.getInstance()
        friends_list = []
        l = []
        
        # Very bad hack. Need to move all these to model.validate
        try:
            # Twitter API doesn't allow to get all friends infor at once.
            # Instead you can only get all friends Ids and the use UserLookup
            # to get full user infor but only in batches of 100 user at once
            follow_list = twitterApi.api.GetFriendIDs(user.twitter)["ids"]

            while len(follow_list) > 100:
                l = l + twitterApi.api.UsersLookup(follow_list[0:100])
                follow_list = follow_list[100:len(follow_list)]
            l = l + twitterApi.api.UsersLookup(follow_list[0:len(follow_list)])

            for friend in l:
                friend_in_db = User.all().filter("twitter =", friend.screen_name)
                if friend_in_db.count() == 1:
                    friends_list.append(friend.screen_name)
            
        except TwitterError: 
            friends_list = ['not_authorized']

        return friends_list
예제 #13
0
	def users(self):
		"""
			List users, for the asmins
		"""
		tmpl = config.lookup.get_template("users.html")
		ulist = list(User.select())
		return tmpl.render(env=config.htmlEnv, users=ulist, session=cherrypy.session)
예제 #14
0
    def get(self):
        async_client = AsyncHTTPClient()
        auth_code = self.get_argument("code", None)
        if auth_code:
            # 第一步 获取access_token
            auth_token_url = self.__build_auth_token_url(auth_code)
            token_response = yield async_client.fetch(auth_token_url)
            access_token, refresh_token = self.__parse_token(token_response)

            # 第二不 得到用户身份信息
            auth_me_url = self.__build_auth_me_url(access_token)
            open_response = yield async_client.fetch(auth_me_url)
            openid = self.__parse_me(open_response)

            # 第三布 获取用户基本信息
            auth_user_url = self.__build_auth_user_url(access_token, openid)
            user_info = yield async_client.fetch(auth_user_url)
            user = self.__parse_user(user_info, access_token, refresh_token, openid)
            # 确认用户是否已经登录过
            try:
                user = User.objects(type='qq', uid=openid)[0]
            except Exception as ex:
                app_log.exception(ex)
            finally:
                user.save()
                self.set_secure_cookie('userid', str(user.id))
                self.set_secure_cookie('type', 'qq')
                self.redirect("/")
        else:
            # 登录失败,跳转到登录页面
            self.redirect("/sigin")
예제 #15
0
def test_clustering():
    me = User.create(name="Jon")
    for x in range(10):
        Photo.create(user_id=me.user_id, name=str(x))

    for x in Photo.objects(user_id=me.user_id):
        print x.name
예제 #16
0
def login():
    user_name = request.form['username'];
    password = request.form['password'];
    for user in User.objects(user_name=user_name):
        if(user.password == password):
            return json.dumps({"result_code":1, "result_message":"Login succeded"})
    return json.dumps({"result_code":0, "result_message":"Login failed"})
예제 #17
0
파일: tests.py 프로젝트: dazbur/languagebot
 def createUser(self, twitter_user, account_status, messages_per_day):
     user = User()
     user.twitter = twitter_user
     user.username = twitter_user
     user.account_status = account_status
     user.messages_per_day = messages_per_day
     user.total_points = 0
     user.put()
     return user
예제 #18
0
 def get_user(self):
     """
     Gets the current user that is logged on based on session data
     """
     session_id = self.get_cookie('session')
     if session_id is not None:
         return User.all().filter('session =', session_id) \
             .filter('session_expiry >', datetime.datetime.now()).get()
예제 #19
0
def getUsers():
    userlist = []
    for user in User.all().order("-total_points").run():
        c = Dictionary.all().\
            filter("twitter_user ="******"username": user.twitter, "points": user.total_points,
                        "wordscount": c})
    return json.dumps(userlist)
예제 #20
0
    def test_isset_user(self, user_data):
        user = self.add_user(**user_data)

        isset_user = User.isset_user(**user_data)

        self.assertTrue(isset_user)
        self.assertEqual(isset_user['user_name'], user.name)
        self.assertEqual(isset_user['user_id'], user.id)
예제 #21
0
def signup(request):
    try:
        cleanData = utils.format_body_params(request.json)

        emailAddress = cleanData.get("emailAddress")
        password = request.json.get("password")
        firstName = cleanData.get("firstName")
        lastName = cleanData.get("lastName")
        phoneNumber = cleanData.get("phoneNumber")

        if not emailAddress:
            return response.json({"error": "No email address provided"}, 400)

        if not password:
            return response.json({"error": "No password provided"}, 400)

        if utils.email_account_exists(emailAddress):
            return response.json(
                {"error": "An account with that email address already exists"}, 400
            )

        if len(password) < request.app.config["MIN_PASS_LENGTH"]:
            return response.json(
                {"error": "Password does not meet required length requirements"}, 400
            )

        user = User(
            firstName=firstName,
            lastName=lastName,
            emailAddress=emailAddress,
            password=utils.encrypt_pass(password),
            phoneNumber=phoneNumber,
        )

        db.session.add(user)
        db.session.commit()

        req_config = request.app.config
        if req_config["SENDGRID_API_KEY"] and req_config["API_ENV"] != "TESTING":
            emails.send_welcome_email(user)

        return response.json(user.serialize(jwt=True), 201)

    except Exception as e:
        return utils.exeption_handler(e, "Signup failed", 400)
예제 #22
0
    def test_get_photos(self):
        user = User.create(name="Jon Haddad")
        photo = Photo.create(user_id=user.user_id,
                             name="Profile Photo",
                             url="https://pbs.twimg.com/profile_images/378800000375781556/2c9dedfd19613c88248d621cbe604857_400x400.jpeg")

        photos = Photo.objects(user_id=user.user_id)

        assert len(photos) == 1
예제 #23
0
파일: user.py 프로젝트: gf2/gf2
 def post(self):
   users = User.gql("WHERE email=:1", self.request.get('email'))
   if users.count() == 0 or \
     users[0].password != hashlib.sha1(self.request.get('password')).hexdigest():
     self.reply({"result": "FAILURE"})
   else:
     # add session    
     session = get_current_session()
     session['me'] = users[0]
     self.reply({"result": "SUCCESS"})
예제 #24
0
파일: user.py 프로젝트: speakless86/gf2
 def post(self):
   users = User.gql("WHERE email=:1", self.request.get('email'))
   if users.count() == 0 or \
     users[0].password != hashlib.sha1(self.request.get('password')).hexdigest():
     self.response.out.write('Login failed.')
   else:
     # add session    
     session = get_current_session()
     session['me'] = users[0]    
     self.response.out.write('Login successfully.')
예제 #25
0
    def post(self):
        id_token = cgi.escape(self.request.get('id_token'))
        gcm_token = cgi.escape(self.request.get('gcm_token'))

        google_id = validate_id_token(id_token)

        if google_id:
            user = User.query(User.google_id == google_id).get()
            if user:
                user.gcm_token = gcm_token
                user.put()
            else:
                user = User(google_id=google_id, gcm_token=gcm_token, status=-1)
                user.put()

            self.response.status = 200
        else:
            self.response.status = 400
            self.response.write(json.dumps(dict(error='invalid token')))
예제 #26
0
def sendMessagesGenerator(TwitterAPI, logging):
    current_time = int(time.time())
    # Are there messages to send out in next SCHEDULERUN seconds?
    next_planned_interval = current_time + SCHEDULERUN
    today = datetime.date.today()

    for lli in LearnList.all().\
        filter("next_serve_time <=", next_planned_interval):
        result = None
        # Don't send messages if user is disabled
        user = User.all().filter("twitter =", lli.twitter_user).\
            filter("account_status =", "enabled").fetch(1)
        if user == []:
            yield result
            # If user has messages in todays list but is disabled now
            # Let's just reschedule it to tomorrow
            lli.next_serve_date = addDays(lli.next_serve_date, 1)
            lli.next_serve_time = sys.maxint
            lli.put()
            continue

        # If there is a question to send, prepare a different
        # Twitter message format
        question = Question.all().filter("lli_ref =", lli).\
            filter("answer_received =", None).fetch(1)

        if question != []:
            message = prepareQuestionMessage(lli)
        else:
            message = prepareTwitterMessage(lli)

        try:
            #status = TwitterAPI.api.PostUpdate(message)
            status = TwitterAPI.api.PostDirectMessage(lli.twitter_user,\
             message)
            result = message
            # For questions we do no recalculate new interval right away
            # We do it when answer is recieved or no received
            # Instead we update Question entity
            if question == []:
                answer_rating = lli.latest_answer_rating
                rescheduleLearnListItem(lli, answer_rating)
            else:
                question[0].question_sent = today
                question[0].question_message_id = status.id
                question[0].put()
                # We also need to make sure this message is not sent again automatically
                # Until answer is recieved or it expires
                lli.next_serve_time = sys.maxint
                lli.put()

        except TwitterError:
            print TwitterError.message
            logging.error("Twitter error when sending message %s" % message)
        yield result
예제 #27
0
파일: app.py 프로젝트: Mita57/StreaMOOR
def register():
    """
    Inserts the information about new user unto the database

    Returns:
        Inserts the information about new user unto the database
    """
    post_data = request.get_json()
    print(post_data)
    today = str(datetime.datetime.now().year) + '-' + str(
        datetime.datetime.now().month) + '-' + str(datetime.datetime.now().day)
    email = post_data.get('email')
    password = post_data.get('password')
    nickname = post_data.get('nickname')
    try:
        User.insert((email, nickname, password, 'null', today, 0, 'sas', False,
                     True, 'gaming', False))
        return jsonify(result='good')
    except:
        return jsonify(result='bad')
예제 #28
0
def edit_user():
    user_content = request.get_json()
    print(user_content)
    user_id = user_content['id']
    firstname = user_content["firstname"]
    lastname = user_content["lastname"]
    email = user_content["email"]
    if User.is_user_with_email_in_user_list(email):
        return "email taken"
    password = user_content["password"]

    user_to_edit = User.get_user_by_id(user_id)
    user_to_edit.set_name(firstname + ' ' + lastname)
    user_to_edit.set_mail(email)
    user_to_edit.set_password(password)
    user_to_edit.save_changes()

    edited_user_in_json = json.dumps(user_to_edit.__dict__, ensure_ascii=False)

    return edited_user_in_json
예제 #29
0
 def setUp(self):
     super(TestUsers, self).setUp()
     self.maxDiff = None
     self.app = create_app()
     self.session = session
     user_obj = User(username="******",
                     email="*****@*****.**",
                     password=pbkdf2_sha256.hash("pass"))
     self.session.add(user_obj)
     self.session.flush()
     self.user_id = int(user_obj.id)
예제 #30
0
    def post(self):
        username = self.request.get('username')
        password = self.request.get('password')

        u = User.login(username, password)
        if u:
            self.login(u)
            self.redirect('/')
        else:
            msg = 'Invalid login'
            self.render('login-form.html', error = msg)
예제 #31
0
def register():
    form_reg = RegistrationForm()
    form_log = LoginForm()
    if form_reg.validate_on_submit():
        user = User(username=form_reg.username.data,
                    password=form_reg.password.data,
                    email=form_reg.email.data)
        db.session.add(user)
        db.session.commit()
        # register and login
        login_user(user, form_log.remember_me.data)
        token = user.generate_confirmation_token()
        send_email(user.email,
                   'Confirm Your Account',
                   'auth/em/confirm',
                   user=user,
                   token=token)
        flash('A confirmation email has been sent to you by email.')
        return redirect(url_for('main.index'))
    return render_template('auth/register.html', form=form_reg)
예제 #32
0
	def newuser(self, username=None, password=None, confpassword=None, realname=None):
		"""
			Creates a user
		"""
		if password=="" or confpassword=="" or username == "" or realname == "":
			return '{"status": "fail", "msg": "Empty fields"}'
		else:
			if password != confpassword:
				return '{"status": "fail", "msg": "The two passwords do not match"}'
			u = users.userExists(username)
			if u != None:
				return '{"status": "fail", "msg": "This user already exists"}'
			
			try:
				u = User(login=username,realName=realname)
				u.changePassword(password)
				u.addGroup("user")
				return '{"status": "ok", "msg": "User<b>' + username + '</b> successfully created !"}'
			except Exception as e:
				return '{ "status": "fail", "msg": "'+str(e)+'"}'
def authenticate(username, password):
    """
    校验用户的密码和数据库记录是否匹配

    :return:
    """
    if username and password:
        hash_pass = User.get_pass(username)
        return hash_pass and hash_pass == hashed(password)
    else:
        return False
예제 #34
0
 def get(self):
     user = current_user()
     if not user:
         self.redirect("/login")
     else:
         parameters = {}
         parameters["total_points"] = User.all().\
             filter("twitter =", user.twitter).get().total_points
         parameters["total_words"] = Dictionary.all().\
             filter("twitter_user =", user.twitter).count()
         self.view(parameters)
예제 #35
0
 def create_user(self):
     user = User.query.filter_by(email=self.email).first()
     if user:
         return "Email already exists"
     if self.email == True:
         # self.password = bcrypt.generate_password_hash(self.password)
         self.password = bcrypt.hashpw(self.password, bcrypt.gensalt())
         user = User(email=self.email, password=self.password)
         db.session.add(user)
         db.session.commit()
     return "Account created"
예제 #36
0
    def put(self, role):
        parser = reqparse.RequestParser()
        parser.add_argument('name',
                            type=str,
                            required=True,
                            help='A user cannot have a blank name')
        parser.add_argument('password',
                            type=str,
                            required=True,
                            help='A user cannot have a blank password')

        data = parser.parse_args()

        if safe_str_cmp(role, 'admin'):
            user = Administrator.find_by_name(data['name'])
            if user is None:
                user = Administrator(name=data['name'],
                                     password=encrypt_password(
                                         data['password']))
            else:
                user.password = encrypt_password(data['password'])

        elif safe_str_cmp(role, 'consumer'):
            user = User.find_by_name(data['name'])
            if user is None:
                user = User(name=data['name'],
                            password=encrypt_password(data['password']))
            else:
                user.password = encrypt_password(data['password'])
        else:
            metrics_req_count.labels(method='PUT',
                                     endpoint='/user',
                                     status_code='400').inc()
            return {'message': 'Invalid role name'}, 400

        user.save_to_db()
        user.refresh()
        metrics_req_count.labels(method='PUT',
                                 endpoint='/user',
                                 status_code='200').inc()
        return user.json_full(), 200
예제 #37
0
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode(
            (Graphics.SCREEN_WIDTH, Graphics.SCREEN_HEIGHT))
        self.clock = pygame.time.Clock()
        self.bg_color = pygame.Color("white")
        self.all_sprites = pygame.sprite.Group()
        self.map = None
        self.user = User()

        self.display_screen_surface = None
        self.display_screen = pygame.font.SysFont('Comic Sans MS', 45)
예제 #38
0
    def get(self):

        if self.get_argument("openid.mode", None):

            result = yield self.get_authenticated_user()
            try:
                user = User.objects(type='google', email=result['email'])[0]
            except Exception as ex:
                app_log.error(ex)
                user = User(uid=str(uuid4()),
                            type='google',
                            email=result['email'],
                            name=result['name'],
                            avatar=getAvatar('email'))
                user.save()

            self.set_secure_cookie('userid', str(user.id))
            self.set_secure_cookie('type', 'google')
            self.redirect("/")
        else:
            yield self.authenticate_redirect()
def create_new_post(blog_id):
    if request.method == 'GET':
        return render_template('new_post.html', blog_id=blog_id)
    else:
        title = request.form['title']
        content = request.form['content']
        user = User.get_by_email(session['email'])

        new_post = Post(blog_id, title, content, user.email)
        new_post.save_to_mongo()

        return make_response(blog_posts(blog_id))
def create_new_blog():
    if request.method == 'GET':
        return render_template('new_blog.html')
    else:
        title = request.form['title']
        description = request.form['description']
        user = User.get_by_email(session['email'])

        new_blog = Blog(user.email, title, description, user._id)
        new_blog.save_to_mongo()

        return make_response(user_blogs(user._id))
예제 #41
0
    def registerme(data):
        try:
            newuser = User(username=data['username'],
                           password=data['password'],
                           email=data['email'])

            db.session.add(newuser)
            db.session.commit()
            return True
        except Exception as error:
            print(error)
            return {"error": error}
예제 #42
0
def form():
    mail = request.form.get("email")
    nom = request.form.get("nom")
    pwd = request.form.get("pwd")
    personne = User(nom, mail, pwd)
    db.session.add(personne)
    db.session.commit()
    return render_template(
            "index.html", 
            message=mail,
            nom=nom
            )
예제 #43
0
def create_new_post(blog_id):
    if request.method == 'GET':
        return render_template('/user_page/new_post.html', blog_id=blog_id)
    else:
        title   = request.form['title']
        content = request.form['description']
        user    = User.get_by_email(session['email'])

        new_post = Post(blog_id, title, content, user._email)
        new_post.save()

        return make_response(get_all_user_posts(blog_id))
예제 #44
0
파일: index.py 프로젝트: FeiPingWang/my_web
def login():
    if request.method == 'POST':
        u = User.validate(request.form)
        if u is None:
            flash('找不到用户或密码错误', 'danger')
        else:
            session['user_id'] = u.id
            session['user_name'] = u.user_name
            logger.info('{} success login'.format(u.user_name))
            flash('登陆成功', 'success')
            return redirect(url_for('index.index'))  # 登录成功
    return render_template('index/login.html')
예제 #45
0
def user(message=None):
    if request.method == "GET":
        if User.validatloginsession():
            Alltasklist = User.get_alltask()
            usertasklist = User.gettaskbyname()
            if message is not None:
                return render_template("user.html",
                                       task=Alltasklist,
                                       usertasklist=usertasklist,
                                       name=session['name'],
                                       Role=session['isadmin'],
                                       message=message)
            else:
                return render_template("user.html",
                                       task=Alltasklist,
                                       usertasklist=usertasklist,
                                       name=session['name'],
                                       Role=session['isadmin'])
        return redirect(
            url_for('login',
                    message="!!!!!!Please login to access the page!!!!!!"))
예제 #46
0
def RecuperarPassword():
    if request.method == "POST":
        RecoverUser = User()
        form = FormRecuperar(request.form)
        if form.validate_on_submit():
            usuarioCorreo = form.usuarioCorreo.data
            lista = RecoverUser.recoverPassword(usuarioCorreo, usuarioCorreo)
            longitud = 18
            valores = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
            p = ""
            p = p.join([choice(valores) for i in range(longitud)])
            yag = yagmail.SMTP('*****@*****.**', 'misiontic2020')
            yag.send(to=lista[1],
                     subject='Recupera tu clave',
                     contents='Utiliza la clave =' + p)
            RecoverUser.recoverPasswordUpdate(p, lista[0])
            return redirect(url_for('users.InicioSesion'))
        else:
            return "Icorrecto"
    else:
        return render_template('recoverPassword.html', form=FormRecuperar())
예제 #47
0
def route_admin_user_add(request):
    form = request.form()
    u = User(form)
    u.role = int(u.role)
    if u.validate_register():
        u.model_add()
    return redirect(request.headers, "/user/list")
예제 #48
0
def add_user():
    if request.method == 'POST':
        try:
            if request.is_json:
                data = request.get_json()
                new_user = User(name=data['name'],
                                grade=data['grade'],
                                address=data['address'],
                                country=data['country'])
                db.session.add(new_user)
                db.session.commit()
                return {
                    "message":
                    f"post {new_user.id} has been created successfully."
                }
            else:
                return {"error": "The request payload is not in JSON format"}
        except Exception as e:
            return {"Error": str(e)}
    elif request.method == 'GET':
        try:
            if len(request.args) == 4 and request.args.get(
                    'name') != None and request.args.get(
                        'grade') != None and request.args.get(
                            'address') != None and request.args.get(
                                'country') != None:
                newUser = User(name=request.args['name'],
                               grade=request.args['grade'],
                               address=request.args['address'],
                               country=request.args['country'])
                db.session.add(newUser)
                db.session.commit()
                return {
                    "message":
                    f"post {newUser.id} has been created successfully."
                }
            else:
                return {"error": "The request payload is not in JSON format"}
        except Exception as e:
            return {"Error": str(e)}
예제 #49
0
def login():
    if request.method == 'GET':
        return redirect(
            url_for('index', incorrectLogin=False, error="Access Denied"))
    if request.method == 'POST':
        try:
            #print(request.form['uni'])
            user = User(request.form["uni"], None, request.form["psw"])
            res = user.findUser()
            pwd = user.getPwd()
            user.db_close()

            if res[0] is True and pwd == request.form['psw']:
                # print("res")
                # print(res[1])
                session['uid'] = res[1]

                return redirect(url_for("LoggedInUsers"))
            else:
                error = "invalid username/password"
                return redirect(
                    url_for("index",
                            incorrectLogin=True,
                            error="incorrect username/password"))
        except Exception as e:
            print(e)
            return redirect(url_for("index"))
예제 #50
0
def cancelWorkout():
    if request.method == 'GET':
        return redirect(
            url_for('index', incorrectLogin=False, error="Access Denied"))
    if 'uid' not in session:
        return redirect(
            url_for('index',
                    incorrectLogin=False,
                    error="please login to access this page"))
    else:
        if (session['uid'] == None):
            return redirect(
                url_for('index',
                        incorrectLogin=False,
                        error="please login to access this page"))
    try:
        s = Schedule()
        u = User()

        uid = session['uid']
        workoutExists = True
        nextWorkout = s.get_user_schedule(
            uid)  #["Treadmill", "tr11", "14:00 - 14:30", "sk4120"]
        print(nextWorkout)
        if nextWorkout == None:
            print("no workouts")
            return redirect(
                url_for('LoggedInUsers', err="you have no workouts scheduled"))
        nextWorkout = nextWorkout[0]

        print(nextWorkout)
        # nextWorkout.append(uni)
        print(nextWorkout)
        if nextWorkout is not None:
            s.cancel_reservation(uid, nextWorkout[1])

            return render_template("cancelWorkout.html",
                                   nextWorkout=nextWorkout,
                                   workoutExists=workoutExists)
        else:
            return redirect(
                url_for('index',
                        incorrectLogin=False,
                        error="server error. Please try again"))

    except Exception as e:
        print(e)

        return redirect(
            url_for('index',
                    incorrectLogin=False,
                    error="server error. Please try again"))
예제 #51
0
    def get(self, id):
        user = User.objects(id=id)[0]
        books = Book.objects(likes__in=[user])
        bgs = self.grouped(books)

        kwargs = {
            "page_heading": unicode(user.name),
            "groups": self.get_groups(),
            "user": user,
            "books": books,
            "bgs": bgs
        }
        self.render('user.html', **kwargs)
예제 #52
0
    def post(cls):
        claims = get_jwt_claims()

        calendario = Calendario()
        calendario.title = request.get_json()['title']
        calendario.start = request.get_json()['start']
        calendario.end = request.get_json()['end']
        calendario.gps = request.get_json()['gps']
        calendario.descricao = request.get_json()['descricao']
        if 'users' in request.get_json():
            calendario.users.clear()
            for user in request.get_json()['users']:
                calendario.users.append(User.find_by_id(user))

        calendario.users.append(User.find_by_id(claims['id']))

        if 'tarefas' in request.get_json():
            calendario.tarefas.clear()
            for tarefa in request.get_json()['tarefas']:
                calendario.tarefas.append(Tarefa.find_by_id(tarefa))
        calendario.save_to_db()
        return Calendario_schema.dump(calendario), 200
예제 #53
0
    def post(self, user_id=None):
        '''POST /users --> add new user

        Fields:
            username: username of the user, must be unique
            name: name of the user
            age: age of the user

        Returns:
            Created user object
        '''
        if user_id:
            abort(404)

        data = UserResource.post_parser.parse_args()

        username = data.get('username')
        name = data.get('name')
        age = data.get('age')

        if username and name:
            user = User(username, name, age)
            try:
                user.save()
            except:
                return {
                    'message': ('Failed to create a new user. '
                                'Please try another username')
                }, 424

            return {
                'message': 'A new user has been created',
                'user': user.to_json()
            }, 201
        else:
            return {
                'message': ('Failed to create a new user. '
                            'All fields are required')
            }, 424
예제 #54
0
    def remove_student(self, **by):
        user = User.find(**by)
        if not user:
            raise NotFound("User not found")

        if user in self.students:
            i = self.students.index(user)
            self.students = self.students[:i] + \
                self.students[i + 1:]
            self.save()
            return user
        else:
            return None
def login():
    error = None
    if request.method == 'POST':
        user_name = request.form['username']
        if User.is_user_with_name_in_user_list(user_name) \
                or User.is_user_with_email_in_user_list(user_name):
            user = User.get_by_name(user_name) if User.is_user_with_name_in_user_list(user_name) \
                else User.get_by_email(user_name)
            if request.form['password'] != user.get_password():
                error = "Wrong password. Try again"
            else:
                session['logged_in'] = True
                session['user_id'] = user.id
                session['user_name'] = user.name
                session['is_admin'] = True if user.is_admin else None
                session['sort_type'] = 'create date'
                session['sort_direct'] = 'desc'
                flash("You are logged in!")
                return redirect(url_for('td_list')) if not user.is_admin else redirect(url_for('admin_panel'))
        else:
            error = "No user with such name. Try again"
    return render_template('login.html', error=error)
예제 #56
0
    async def get(self, candidate_id, *args, **kwargs):
        query = User.get_vote_rank(candidate_id)
        print(query.sql()[0])
        ranks = await objects.execute(query)

        ret = []
        for rank in ranks:
            ret.append(
                dict(voter_avatar=rank.avatar,
                     voter_nickname=rank.nickname,
                     number_of_votes=int(rank.number_of_votes),
                     vote_rank=rank.vote_rank))
        self.finish(json.dumps(ret))
예제 #57
0
def unfollow(username):
    if not username and len(username) > 36:
        flash("User Not Found!")
        return redirect('/', 302)

    if current_user.is_authenticated:
        user = User.get_user_info(username=username)
        if user and current_user.unfollow_user(user):
            return redirect(f'/player/{username}')
        flash("User Not Found!")
        return redirect('/', 302)
    flash('Please Login before this action!')
    return redirect('/', 302)
예제 #58
0
 def create_user(self, user_data):
     collection = self.db.users
     user = collection.find_one({'username': user_data['username']})
     if user:
         logging.warning('User already exists')
         return 'User already exists'
     elif not validate_user(user_data):
         logging.warning('User data invalid')
         return 'User data invalid'
     new_user = User(user_data)
     collection.insert_one(new_user.__dict__)
     logging.info('User created')
     return 'User created successfully'
예제 #59
0
async def create_user(request):
    json_data = request.json
    username = json_data.get("username", None)
    password = json_data.get("password", None)
    if not username or not password:
        raise ValueError
    user = User.create_user(username, password)
    data = {
        "id": user.id,
        "username": user.username,
        "password": user.password
    }
    return response.json({"data": data})
예제 #60
0
def signup():

    if request.method == 'POST':

        username = request.form['username']
        email = request.form['email']
        password = request.form['password']

        if User.query.filter_by(email=email).first():
            print('Email already exists')
            return redirect(url_for('signup'))
        else:
            hashed_password = generate_password_hash(password)

            user = User(username=username,
                        email=email,
                        password=hashed_password)
            user.create_record()
            print('Account created successfully')
            return redirect(url_for('signup'))

    return render_template('signup.html')