Esempio n. 1
0
    def update_faculty_table(dept):

        # Do not display table for aggregate views
        if dept in ['AS', 'HUM', 'NS', 'SS']:
            return [], {'display': 'none'}

        # Do not display table without chair-level access
        # to the selected department
        current_user = User()
        if dept not in current_user.deptprofile_access('dept_chair'):
            return [], {'display': 'none'}
        else:
            resp = table.query(KeyConditionExpression=
                               'PK = :pk AND SK BETWEEN :lower AND :upper',
                               ExpressionAttributeValues={
                                   ':pk':
                                   f'DEPT#{dept}',
                                   ':lower':
                                   f'DATA#FACULTY_LIST#{MAX_FISCAL_YEAR}',
                                   ':upper':
                                   f'DATA#FACULTY_LIST#{MAX_FISCAL_YEAR}$',
                               },
                               ScanIndexForward=True)

            return resp['Items'], {'display': 'inline'}
Esempio n. 2
0
 def init_data(self):
    #default test user
    demo =User(
          first_name=u'demo',
          last_name=u'demo',
          user_name=u'demo',
          password=u'123456',
          role_code=ADMIN,
          status_code=ACTIVE,
          user_settings=UserSettings(
              sex_code=MALE,
              phone='555-555-5555',
              bio=u'just a demo guy'))
    email = Email(address= "*****@*****.**", is_primary=True, status_code=VERIFIED) 
    demo.add_email(email)
    
    db.session.add(demo)
    db.session.add(email)
    db.session.commit()
    
    """Add in post categories"""
    for c in CATEGORIES:
       hashtag = Hashtag(name = c)      
       db.session.add(hashtag)
    db.session.commit()
    
    self.demo_user= demo
    
    '''Add in circles'''
    ucla = Circle(name=u'ucla', description=u'ucla.edu emails only')
    ucla.add_member(demo)
    db.session.add(ucla)
    db.session.commit()
Esempio n. 3
0
def load_user(id):
    a = teach.find_one({"_id": id})
    if a is not None:
        return User(id=a.get("_id"), password=a.get("pword"), type="T")
    else:
        a = stu.find_one({"_id": id})
        return User(id=a.get("_id"), password=a.get("pword"), type="S")
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = UserLoginForm()
    search_form = SearchForm()
    if form.validate_on_submit():
        user = mongo.db.users.find_one({'username': form.username.data})
        if user and User.check_password(user['password'], form.password.data):
            user_obj = User(user['username'], user['email'], user['_id'],
                            user['is_admin'])
            login_user(user_obj)
            # accesses the 'next page' query string to determine which url user wanted to visit
            # before being redirected to the login page. If no next page was given then redirects user
            # to the index page. 'url_parse.netloc' prevents malicious redirect attacks. This prevents
            #redirects by ensuring that the url is relative to the page.
            next_page = request.args.get('next')
            if not next_page or url_parse(next_page).netloc != '':
                next_page = url_for('index')
            return redirect(next_page)
        else:
            flash('Wrong username or password', 'warning')
    return render_template('loginform.html',
                           form=form,
                           search_form=search_form,
                           title='Login')
Esempio n. 5
0
 def setUp(self):
     """Set up test"""
     self.user = User()
     self.current_users = USERS
     self.user_email = "*****@*****.**"
     self.username = "******"
     self.password = "******"
Esempio n. 6
0
    def init_data(self):
        #default test user
        demo = User(first_name=u'demo',
                    last_name=u'demo',
                    user_name=u'demo',
                    password=u'123456',
                    role_code=ADMIN,
                    status_code=ACTIVE,
                    user_settings=UserSettings(sex_code=MALE,
                                               phone='555-555-5555',
                                               bio=u'just a demo guy'))
        email = Email(address="*****@*****.**",
                      is_primary=True,
                      status_code=VERIFIED)
        demo.add_email(email)

        db.session.add(demo)
        db.session.add(email)
        db.session.commit()
        """Add in post categories"""
        for c in CATEGORIES:
            hashtag = Hashtag(name=c)
            db.session.add(hashtag)
        db.session.commit()

        self.demo_user = demo
        '''Add in circles'''
        ucla = Circle(name=u'ucla', description=u'ucla.edu emails only')
        ucla.add_member(demo)
        db.session.add(ucla)
        db.session.commit()
Esempio n. 7
0
class ShoppingListTests(unittest.TestCase):
    """
    Class to hold test cases
    """
    def setUp(self):
        """
        Setting up User before testing
        """
        self.user = User()

    def tearDown(self):
        """
        Clearing dataset after testing
        """
        del self.user

    def test_if_user_exists(self):
        """
        Test case to check if a user already exists
        """
        self.user.create_user("random", "pass123", "pass123")
        result = self.user.create_user("random", "pass123", "pass123")
        self.assertEqual(result, "The user already exists.")

    if __name__ == '__main__':
        unittest.main()
Esempio n. 8
0
def initdb():
    """Init/reset database."""

    db.drop_all(bind=None)
    db.create_all(bind=None)

    admin = User(
        first_name=u"admin",
        last_name=u"admin",
        user_name=u"admin",
        password=u"123456",
        role_code=ADMIN,
        status_code=ACTIVE,
        user_settings=UserSettings(
            sex_code=MALE, age=10, phone="555-555-5555", bio=u"admin Guy is ... hmm ... just a admin guy."
        ),
    )
    email = Email(address="*****@*****.**", is_primary=True, status_code=VERIFIED)
    admin.add_email(email)
    db.session.add(admin)
    db.session.add(email)
    db.session.commit()

    hashtag = None
    """Add in all post hashtag"""
    for (key, id) in CATEGORIES.iteritems():
        hashtag = Hashtag(id=id, name=key)
        db.session.add(hashtag)
    db.session.commit()

    # generate 1000 random post
    """
    for x in range(0,1000):
      post = Post(name='test-'+str(x), price=10, description='AOH LALAL')
      post.user_id = admin.id
      post.add_hashtag(hashtag)
      db.session.add(post)
   
      db.session.commit()

      chat = Chat(buyer= admin)
      msg = ChatMessage(body = "TEST MESSAGE", created_by = admin.id)
      post.add_chat(chat)
      chat.add_message(msg)
      db.session.commit()

    db.session.commit()
    """

    # Add in ucla circle
    ucla = Circle(name=u"ucla", description=u"ucla.edu emails only")
    ucla.add_member(admin)
    db.session.add(ucla)
    db.session.commit()

    ucla_info = CollegeInfo(
        circle_id=ucla.id, domain=u"ucla.edu", fb_group_id=267279833349705, fb_sell_id=267375200006835
    )
    db.session.add(ucla_info)
    db.session.commit()
Esempio n. 9
0
def logview():
    if current_user.is_authenticated:
        if current_user.type == 'S':
            return redirect(url_for('stuhome'))
        else:
            return redirect(url_for('profhome'))
    l1 = LoginForm()
    if l1.validate_on_submit():
        user = teach.find_one({"_id": l1.id.data})
        if user is not None and l1.password.data == user.get("pword"):
            t = User(id=user.get("_id"), password=user.get("pword"), type="T")
            login_user(t, duration=datetime.timedelta(hours=1))
            return redirect(url_for('profhome'))
        elif user is not None:
            flash('Invalid username/password combination.')
        else:
            user = stu.find_one({"_id": l1.id.data})
            if user is not None and l1.password.data == user.get("pword"):
                t = User(id=user.get("_id"),
                         password=user.get("pword"),
                         type="S")
                login_user(t, duration=datetime.timedelta(hours=1))
                return redirect(url_for('stuhome'))
            else:
                flash('Invalid username/password combination.')
    return render_template('login.html',
                           form=l1,
                           title='Log in.',
                           template='login-page',
                           body="Log in with your User account.")
Esempio n. 10
0
	def like(self, liking_user : User):
		if liking_user._id not in self.liked_by:
			chat = spawn_chat(self.user, liking_user._id)
			if chat.accept(liking_user._id):
				from app.notifications import Notification, UserNotifications
				note = Notification(User.get({"_id" : self.user}), User.get({"_id" : liking_user._id}), Notification.ACTION_LINKED)
				UserNotifications.notify(note)
				note = Notification(liking_user, User.get({"_id" : self.user}), Notification.ACTION_LINKED)
				UserNotifications.notify(note)
				pass #mutual like
			chat.save()
			self.liked_by.append(liking_user._id)
Esempio n. 11
0
def GetUserFromToken(tok: str) -> User:
    usr = User()
    try:
        tokenObj = jwt.decode(tok, os.environ['SECRET'], algorithms=['HS256'])
    except:
        print("problem decoding token")
        return usr

    usr.id = tokenObj["id"]
    usr.username = tokenObj["username"]
    usr.email = tokenObj["email"]
    return usr
Esempio n. 12
0
def serve_sal_layout():

    current_user = User()
    depts = current_user.salary_access()

    if depts:

        logger.log_access(has_access=True)

        # Create a list of dropdown options based on user permissions
        # Do this here to call salary_access only once
        dept_dropdown_options = []
        for option in ALL_DEPT_DROPDOWN_OPTIONS:
            if option['value'].strip('_') in depts:
                dept_dropdown_options.append(option)

        layout = html.Div([
            serve_navbar(),
            html.Div(
                [
                    header,
                    html.Div(id='test-div'),
                    serve_filters(dept_dropdown_options),
                    chart,
                    table,
                ],
                className='container pb-5',
            ),
        ])

    else:

        # Log that a user accesssed this view and was NOT authorized
        logger.log_access(has_access=False)

        no_access_alert = dbc.Alert([
            html.H5('You don\'t have access to this page.',
                    className='alert-heading'),
            html.P(
                'Please reach out to Timur Gulyamov (tg2648) to get access.',
                className='mb-0',
            ),
        ],
                                    color='warning',
                                    className='mt-3')

        layout = html.Div([
            serve_navbar(),
            html.Div([no_access_alert], className='container'),
        ])

    return layout
Esempio n. 13
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(login=form.login.data)
        user.set_password(form.password.data)

        register_user(user.login, user.password_hash)

        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
Esempio n. 14
0
class userRegistrationDetailsTestCase(unittest.TestCase):
    def setUp(self):
        self.myUser=User(1, 2, 3, 4, 2)

    def test_typeOfFields(self):
        result=self.myUser.create_user(1, 2, 3, 4, 2)
        self.assertEquals("Invalid input. Enter character elements", result)
    def test_emptyFields(self):
        result=self.myUser.create_user("", "","" , "", "")
        self.assertEquals("Kindly fill out all the form fields", result)
    def test_lengthPasswordLessThanEightCharacters(self):
        result=self.myUser.create_user("sue", "smith","sue" , "sue@outlookcom", "vg")
        self.assertEquals("Password length too small", result)
Esempio n. 15
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Welcome to Pedagogy. You\'re now registered. Please log in.')
        return redirect(url_for('login'))

    return render_template('register.html', form=form)
 def test_authenticate(self):
    guy = self.good_guy
    db.session.add(guy)
    db.session.commit()
    user,authenticated = User.authenticate(guy.user_name, self.correct_password)
    self.assertEqual(guy, user)
    self.assertTrue(authenticated)
    
    user,authenticated = User.authenticate(guy.user_name, 'asdfasd')
    self.assertEqual(guy, user)
    self.assertFalse(authenticated)
    
    user,authenticated = User.authenticate('random', 'asdfasd')
    self.assertIsNone(user)
    self.assertFalse(authenticated)
Esempio n. 17
0
 def setUp(self):
     self.create_app()
     self.app = app.test_client()
     db.create_all()
     pw = generate_password_hash("admin123456", method='sha256')
     db.session.add(User(username="******", password=pw))
     db.session.commit()
Esempio n. 18
0
    def test_authenticate(self):
        guy = self.good_guy
        db.session.add(guy)
        db.session.commit()
        user, authenticated = User.authenticate(guy.user_name,
                                                self.correct_password)
        self.assertEqual(guy, user)
        self.assertTrue(authenticated)

        user, authenticated = User.authenticate(guy.user_name, 'asdfasd')
        self.assertEqual(guy, user)
        self.assertFalse(authenticated)

        user, authenticated = User.authenticate('random', 'asdfasd')
        self.assertIsNone(user)
        self.assertFalse(authenticated)
Esempio n. 19
0
	def current_user(self):
		from app.users import User
		from bson import ObjectId
		if "token" not in session:
			raise Exception(message="Need token")
		token = decode_token(session["token"])
		return User.get({"_id" : ObjectId(token["identity"]['id'])}, {"hash" : 0})
Esempio n. 20
0
def action_thing(uid, action):
	if ObjectId(uid) == current_user._id:
		raise APIException(message="You cant Like, Block or report yourself")
	if action == "like":
		tel = Telemetry.get({"user" : ObjectId(uid)})
		tel.like(current_user)
		tel.save()
		note = Notification(current_user, User.get({"_id" : ObjectId(uid)}), Notification.ACTION_LIKE)
		UserNotifications.notify(note)
		return APISuccessMessage(displayMessage={"message" : "Liked"}, update={"action" : "replace",
			"subject" : "#like", "fn" : "has_been_liked"}).messageSend()
	elif action == "block":
		from app import resolve_user
		blocked = resolve_user(ObjectId(uid))
		ttl = Telemetry.get({"user" : current_user._id})
		ttl.block(blocked)
		ttl.save()
		return APISuccessMessage(displayMessage={
			"message" : "This user is now %s" % ( "blocked" if blocked._id in ttl.blocked else "unblocked")}, 
			update={
				"action" : "change",
				"subject" : "#block", 
				"fn" : "blocking", 
				"data": "%s" %("Block" if not blocked._id in ttl.blocked else "Unblock") 
			}).messageSend()
	elif action == "report":
		#Something or the other, need to think about this
		
		pass
	else:
		raise APIException(message="Invalid option")
	return "OK"
	
Esempio n. 21
0
    def get(self, username):

        user = User.get_user(username)

        if not user:
            return user['data'], 404
        return user['data'], 200
Esempio n. 22
0
def authenticate(username, password):
    print username
    print password
    user = UserModel.find(_username=username)
    print user
    if user is not None:
        if user.verify_password(password):
            return user
Esempio n. 23
0
def authenticate(username, password):
    print username
    print password
    user = UserModel.find(_username=username)
    print user
    if user is not None:
        if user.verify_password(password):
            return user
Esempio n. 24
0
    def post(self):
        print request.json['token']
        token = PasswordToken.find(_token=request.json['token'])
        if token is not None:
            user = User.find(id=token.user_id)

            user.password = request.json['password']
            return '', 200
        abort(400)
Esempio n. 25
0
    def post(self):
        print request.json['token']
        token = PasswordToken.find(_token=request.json['token'])
        if token is not None:
            user = User.find(id=token.user_id)

            user.password = request.json['password']
            return '', 200
        abort(400)
Esempio n. 26
0
def serve_req_dropdown():

    current_user = User()
    current_user_reqs = current_user.searchcom_access()

    req_dropdown_options = build_req_dropdown_options(current_user_reqs)

    req_dropdown = html.Div(dbc.FormGroup([
        dbc.Label("Select search:", html_for="req-num-dropdown"),
        dcc.Dropdown(id='req-num-dropdown',
                     options=req_dropdown_options,
                     value=req_dropdown_options[0]['value'],
                     multi=False,
                     clearable=False),
    ]),
                            className='mt-3')

    return req_dropdown
Esempio n. 27
0
 def setUp(self):
     """set up for each test"""
     APP.config['TESTING'] = True
     APP.config['WTF_CSRF_ENABLED'] = False
     self.test_app = APP.test_client()
     self.user_email = "*****@*****.**"
     self.username = "******"
     self.user_password = "******"
     self.user = User()
Esempio n. 28
0
def initdb():
    """Init/reset database."""

    db.drop_all(bind=None)
    db.create_all(bind=None)

    admin = User(first_name=u'admin',
                 last_name=u'admin',
                 user_name=u'admin',
                 password=u'gFcPU5XB',
                 role_code=ADMIN,
                 status_code=ACTIVE,
                 user_settings=UserSettings(sex_code=MALE,
                                            age=10,
                                            phone='555-555-5555',
                                            bio=u''))
    email = Email(address="*****@*****.**",
                  is_primary=True,
                  status_code=VERIFIED)
    admin.add_email(email)
    db.session.add(admin)
    db.session.add(email)
    db.session.commit()

    hashtag = None
    """Add in all post hashtag"""
    for (key, id) in CATEGORIES.iteritems():
        hashtag = Hashtag(id=id, name=key)
        db.session.add(hashtag)
    db.session.commit()

    #Add in ucla circle
    ucla = Circle(name=u'ucla', description=u'ucla.edu emails only')
    ucla.add_member(admin)
    db.session.add(ucla)
    db.session.commit()

    ucla_info = CollegeInfo(circle_id=ucla.id,
                            domain=u'ucla.edu',
                            fb_group_id=267279833349705,
                            fb_sell_id=267375200006835)
    db.session.add(ucla_info)
    db.session.commit()
Esempio n. 29
0
def public_profile(uid):
	id = ObjectId(uid)
	profile_user = User.get({"_id" : id})
	profile_telemetry = Telemetry.get({"user" : id})
	view_tel = Telemetry.get({"user" : current_user._id})
	account = Account.get({"user" : id})
	if not current_user._id == id and current_user._id not in profile_telemetry.viewed_by:
		profile_telemetry.view(current_user)
		profile_telemetry.save()
		UserNotifications.notify(Notification(current_user, profile_user, Notification.ACTION_VIEW))
	return render_template("account/pages/profile.html", user=profile_user, viewer=current_user, account=account, telemetry=profile_telemetry, showMeta=current_user._id == id, viewer_telemetry=view_tel)
Esempio n. 30
0
 def message(self):
     auth = User.get({"_id": self.author}, {"uname": 1})
     if self.action == self.ACTION_LIKE:
         return "%s liked your page" % auth["uname"]
     if self.action == self.ACTION_LINKED:
         return "%s and your account is now linked, you can chat" % auth[
             "uname"]
     if self.action == self.ACTION_VIEW:
         return "%s looked at your profile" % auth["uname"]
     if self.action == self.ACTION_MESSAGE:
         return "%s left you a message" % auth["uname"]
Esempio n. 31
0
 def __init__(self, *args, **kwargs):
     super(TestUserModel, self).__init__(*args, **kwargs)
     self.correct_password = u'123456'
     self.good_guy = User(first_name=u'good',
                          last_name=u'guy',
                          user_name=u'test',
                          password=self.correct_password,
                          role_code=USER,
                          status_code=ACTIVE,
                          user_settings=UserSettings(sex_code=MALE))
     self.good_girl = User(first_name=u'good',
                           last_name='girl',
                           user_name=u'crazy_girl',
                           password=self.correct_password,
                           role_code=USER,
                           status_code=INACTIVE,
                           user_settings=UserSettings(sex_code=FEMALE))
     self.good_girl_email = Email(address="*****@*****.**",
                                  is_primary=False,
                                  status_code=VERIFIED)
Esempio n. 32
0
def initdb():
    """Init/reset database."""

    db.drop_all(bind=None)
    db.create_all(bind=None)

    admin = User(
            first_name=u'admin',
            last_name=u'admin',
            user_name=u'admin',
            password=u'gFcPU5XB',
            role_code=ADMIN,
            status_code=ACTIVE,
            user_settings=UserSettings(
                sex_code=MALE,
                age=10,
                phone='555-555-5555',
                bio=u''))
    email = Email(address= "*****@*****.**", is_primary=True, status_code=VERIFIED) 
    admin.add_email(email)
    db.session.add(admin)
    db.session.add(email)
    db.session.commit()
    
        
    hashtag = None
    """Add in all post hashtag"""
    for (key,id) in CATEGORIES.iteritems():
      hashtag = Hashtag(id=id, name = key)     
      db.session.add(hashtag)
    db.session.commit()
    
    #Add in ucla circle
    ucla = Circle(name=u'ucla', description=u'ucla.edu emails only')  
    ucla.add_member(admin)
    db.session.add(ucla)   
    db.session.commit()
       
    ucla_info = CollegeInfo(circle_id = ucla.id, domain=u'ucla.edu',fb_group_id=267279833349705, fb_sell_id=267375200006835)
    db.session.add(ucla_info)
    db.session.commit()
Esempio n. 33
0
    def notify(notif: Notification):
        tel = Telemetry.get({"user": notif.reciever})
        if notif.author in tel.blocked:
            return

        print("Sending notification")
        from .socket import Notifier
        Notifier.push_notification(notif)
        Notifier.push_alert_count(
            notif.reciever,
            len(UserNotifications.get_unread(User(_id=notif.reciever))))
        notif.save()
Esempio n. 34
0
def reset_password(token):
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    user = User.verify_reset_password_token(token)
    if not user:
        return redirect(url_for('index'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        user.set_password(form.password.data)
        db.session.commit()
        flash('Your password has been reset.')
        return redirect(url_for('login'))
    return render_template('reset_password.html', form=form)
Esempio n. 35
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('email', type=str, required=True, location='json')
        parser.add_argument('password', type=str, required=True,
                            location='json')

        data = parser.parse_args()
        user = User.generate_auth_token(data['email'], data['password'])

        if not user['status']:
            return user['data'], 401

        return user['data'], 200
Esempio n. 36
0
def get_users():
    users = User.get({
        "active": True,
        "login_location.region_name": {
            "$ne": None
        }
    })
    print("Sorting by region")
    for i in users[:5]:
        print(i.login_location)
    users.sort(key=lambda x: x.login_location["region_name"] == current_user.
               login_location["region_name"])
    print("Got users")
    return users
Esempio n. 37
0
def serve_fif_archive_layout():

    current_user = User()

    if current_user.has_fif_archive_access():
        # If user has elevated access, serve admin view

        logger.log_access(has_access=True)

        layout = html.Div([
            serve_navbar(),
            html.Div(
                [
                    header,
                    serve_admin_fif_list(),
                ],
                className="container pb-5",
            ),
        ])

    else:

        # Otherwise, serve faculty view
        logger.log_access(has_access=False)

        layout = html.Div([
            serve_navbar(),
            html.Div(
                [
                    header,
                    serve_faculty_fif_list(current_user.uni),
                ],
                className="container pb-5",
            ),
        ])

    return layout
Esempio n. 38
0
def download(key):
    """
    Downloads a file from S3 based on the key in the path
    """
    logger = DynamoAccessLogger('facgov_download')
    current_user = User()

    # Check access, no access if an empty list is returned from a User class
    if current_user.has_facgov_access():

        client = current_app.config['S3_RESOURCE']
        bucket = client.Bucket(current_app.config['FACGOV_BUCKET'])

        # Redirect to base url for keys that end with '/' which are valid S3 keys but are not files
        if key.endswith('/'):
            return redirect(bp.url_prefix)

        try:
            file_obj = bucket.Object(key).get()
        except client.meta.client.exceptions.NoSuchKey:  # per boto3 docs
            logger.log_access(has_access=False, downloaded_object=key)
            raise NotFoundError(f'File {file_name(key)} not found.')

        logger.log_access(has_access=True, downloaded_object=key)
        return Response(file_obj['Body'].read(),
                        mimetype=file_type(key),
                        headers={
                            "Content-Disposition":
                            "inline; filename={}".format(file_name(key))
                        })

    else:

        logger.log_access(has_access=False, downloaded_object=key)
        raise ForbiddenError('You do not have access to this page. \
                              Please reach out to Timur Gulyamov (tg2648) to get access.'
                             )
Esempio n. 39
0
    def post(self):

        parser = reqparse.RequestParser()
        parser.add_argument('email', type=str, required=True, location='json')
        parser.add_argument('username', type=str, required=True,
                            location='json')
        parser.add_argument('password', type=str, required=True,
                            location='json')

        data = parser.parse_args()
        user = User.create_user(data['email'], data['username'],
                                data['password'])

        if not user['status']:
            return user['data'], 409

        return {'message': 'success'}, 201
Esempio n. 40
0
    def get(self, id):
        user = User.find(id=id)
        user.password = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(32))
        user.save()

        token = PasswordToken()
        token._token = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(32))
        token.user_id = user.id
        token.save()

        msg = Message()
        msg.html = render_template('force_email.html', token=token._token)
        msg.recipients = [user.email]
        msg.subject = 'Action Required: CCMA Password Reset'

        mail.send(msg)

        return '', 200
Esempio n. 41
0
def load_user(payload):
    user = UserModel.find(id=payload['user_id'])
    return user
Esempio n. 42
0
    def get(self):
        users = User.get_all_user()

        return users, 200
 def test_is_user_name_taken(self):
    guy = self.good_guy
    db.session.add(guy)
    db.session.commit()
    self.assertTrue(User.is_user_name_taken(guy.user_name))
    self.assertFalse(User.is_user_name_taken(self.good_girl.user_name))