Пример #1
0
def login():
    if current_user is not None and current_user.is_authenticated:
        return redirect(url_for('index'))
    login_form = LoginForm()
    register_form = RegisterForm()

    next_redir = request.args.get('next')
    if not is_safe_url(next_redir):
        next_redir = None

    if login_form.login.data and login_form.validate_on_submit():
        user = User.get_by_email_pass(login_form.email.data, login_form.password.data, data_base)
        if user is None:
            flash('Invalid login. Please try again.')
            return redirect(url_for('login', next_redir=next_redir) if next_redir else url_for('login'))
        
        login_user(user, remember=login_form.remember_me.data)
        session['remember_me'] = login_form.remember_me.data
        return redirect(next_redir or url_for('index'))

    if register_form.register.data and register_form.validate_on_submit():
        
        user = User.register_new_user(register_form.email.data, register_form.password.data, register_form.first_name.data, register_form.second_name.data, data_base)
        if user is None:
            flash('This email already registered. Please try again.')
            return redirect(url_for('login', next_redir=next_redir) if next_redir else url_for('login'))
        
        login_user(user, remember=False)
        session['remember_me'] = False
        return redirect(next_redir or url_for('index'))
        
    return render_template('login.html',
        login_form=login_form,
        register_form=register_form)
Пример #2
0
def index():
    user_name = None
    if 'user_id' in session:
        user_id = session['user_id']
        if User.get(user_id):
            session['user_name'] = User.get(user_id).username
    return render_template('homepage.html', username=session['user_name'])
Пример #3
0
def load_session_user():
    if "user_id" in session:
        user = User.get(session["user_id"])
    else:
        user = User.get("anon")

    g.user = user
Пример #4
0
 def post(self):
     args = parser.parse_args()
     password = args.get('password')
     username = args.get('username')
     name = args.get('name')
     logging.debug("sign up {}".format(username))
     people = People.getbyusername(username)
     if people:
         logging.debug("username already taken")
         raise UserAlreadyExistsError
     else:
         people = People.create(name, username)
         people.get().genpass(password)
         user = User.get(username)
         if user is None:
             user = User.get(username)
             logging.warning("User get retry")
         if user is not None:
             login_user(user, remember=True)
         else:
             logging.warning("Still not found")
         return {
             'id': people.id(),
             "username": username,
             "name": name,
             "admin": False
         }
Пример #5
0
def manage():
    if 'user_id' in session:
        user_id = session['user_id']
        if User.get(user_id):
            session['user_name'] = User.get(user_id).username
    if request.method == 'POST':
        modulenames = []
        try:
            if request.form['moudle1']:
                modulenames.append(request.form['moudle1'])
        except:
            pass
        try:
            if request.form['moudle2']:
                modulenames.append(request.form['moudle2'])
        except:
            pass
        try:
            if request.form['moudle3']:
                modulenames.append(request.form['moudle3'])
        except:
            pass
        username = session['user_name']
        print(modulenames)
        config_checksa(modulenames)
    return render_template('manage.html', username=session['user_name'])
Пример #6
0
 def test_serialize(self):
     db = StringIO()
     User('James', 'Secret007', 'Active').serialize(db)
     self.assertEquals(db.getvalue(), 'James\tSecret007\tActive\n')
     User('user', 'T3stpass').serialize(db)
     self.assertEquals(
         db.getvalue(), 'James\tSecret007\tActive\n'
         'user\tT3stpass\tInactive\n')
Пример #7
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user_name = form.username.data
        password = form.password.data
        remember_me = form.remember_me.data
        user = User(user_name)
        if user.verify_password(password):
            login_user(user)
            session['project'] = user.get_project()
            return redirect(request.args.get('next') or url_for('manage'))
    return render_template('login.html', title="Sign In", form=form)
Пример #8
0
def login():
    next = request.args.get('next')
    form = LoginForm()
    if form.validate_on_submit():
        user = User(mongo, form.data['username'], password=form.data['password'])
        if not user.is_authenticated():
            flash('Brugernavn eller password forkert')
            return render_template('login.html', form=form, next=next)
            #return redirect('/login')
        else:
            res = login_user(user)
            return redirect('/')
    return render_template("login.html", form=form)
Пример #9
0
    def login(self, msg=False):
        clear()
        print('---Log in---')
        if msg is not False:
            print(f"!! {str(msg)} !!")
        uname = input('Username: '******'password: '******'Username or password incorrect')
        else:
            self.logged_in(res)
Пример #10
0
 def post(self):
     current_user = users.get_current_user()
     user_color = self.request.get('color')
     user = User(first_name=self.request.get('first_name'),
                 last_name=self.request.get('last_name'),
                 email=current_user.email(),
                 color=user_color)
     user_key = user.put()
     family = Family(members=[user_key])
     family.put()
     profile_template = the_jinja_env.get_template('templates/profile.html')
     profile_dict = {"last_name": user.last_name, "family": family}
     self.response.write(profile_template.render(profile_dict))
     time.sleep(0.1)
     self.redirect("/profile")
Пример #11
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('listing'))
    form = RegistrationForm()
    if form.validate_on_submit():
        existing_email = users.find_one({'email': form.email.data})
        # Create new user only if email is not already in use
        if existing_email is None:
            hashed_password = bcrypt.generate_password_hash(
                                form.password.data
                                ).decode('utf-8')
            users.insert_one({
                "username": form.username.data,
                "email": form.email.data,
                "password": hashed_password,
            })
            # Log in once user is created in db
            user = users.find_one({'email': form.email.data})
            login_user(User(user), remember=False)
            flash(f'Account created for {form.username.data}.', 'success')
            return redirect(url_for('listing'))
        else:
            flash(f'Something went wrong with the information provided.',
                   'danger')

    return render_template(
                            'pages/registration.html',
                            title="Registration",
                            form=form)
Пример #12
0
 def _verify_creating_fails_with_invalid_password(self, pwd, msg):
     try:
         User('testuser', pwd)
         self.fail("Creating user with password '%s' should have failed "
                   "with error message '%s' but it passed." % (pwd, msg))
     except ValueError, err:
         self.assertEquals(str(err), msg)
Пример #13
0
def login() -> Response:
    """Login route. Processes post messages from the login form.

    :return: A redirect to the landing page.
    """

    # build the redirect, regardless of the result, we're currently always redirecting to the landing
    url: str = url_for('root')
    output: Response = redirect(url)

    # validate form data
    form: LoginForm = LoginForm()
    if not form.validate_on_submit():
        flash('User login failed.', 'danger')
        return output

    name: str = form.name.data
    password: str = form.password.data

    with db_session:
        # validate user & password
        model: UserModel = UserModel.get(name=name)
        if not model or not check_password_hash(model.password_hash, password):
            flash('User login failed.', 'danger')
            return output

        # login the user
        user: User = User(model.user_id, model.name)
        login_user(user, remember=True)
        flash(f'User "{name}" logged in.', 'success')

        return output
Пример #14
0
def login():
    # Redirect to listing page if user is logged in
    if current_user.is_authenticated:
        return redirect(url_for('listing'))
    form = LoginForm()
    if form.validate_on_submit():
        user = users.find_one({'email': form.email.data})
        # If user exists and password matches password in db,
        # log in and create a user session
        if user and bcrypt.check_password_hash(
                        user['password'],
                        form.password.data.encode('utf-8')):
            username = user['username']
            # Save session, even after browser is closed
            login_user(User(user), remember=form.remember.data)

            # Checks where to redirect the user after login
            next_page = request.args.get('next')
            flash(f'Welcome to squirrel, {username}.', 'success')

            # If unauthorized page has been accessed before being logged in,
            # redirect to it after login if it is safe
            if next_page and is_safe_url(next_page, socket.gethostname()):
                return redirect(next_page)

            # If not, redirect to the listing page
            else:
                return redirect(url_for('listing'))
        else:
            flash(
                'Login unsucessful, please check email and password.',
                'danger')

    return render_template('pages/login.html', title="Login", form=form)
Пример #15
0
    def create_acount(self, msg=False):
        clear()
        print('---Create acount---')
        if msg is not False:
            print(f"!! {str(msg)} !!")

        uname = input('Username: '******'password: '******'user_exists':
            # try again
            self.create_acount('User already exists')
        else:
            self.logged_in(res)
Пример #16
0
 def login(self):
     user_data = json.loads(request.data)
     print(user_data)
     username = user_data['cn']
     password = user_data['password']
     result = User.try_login(username, password)
     return result
Пример #17
0
    def test_create_new_user(self):

        '''
        test_create_new_user test case to test if a user is being created
        '''

        line = "user|passwd"
        self.assertEqual(line,User.create_user(self))
Пример #18
0
def register():
    form = RegisterForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            user_name = form.username.data
            password = form.password.data
            project = form.project.data
            user = User(user_name)
            user.register(password, project)
        return render_template('login.html',
                               title="Sign In",
                               form=form,
                               username=session['user_name'])
    return render_template('register.html',
                           title="Register",
                           form=form,
                           username=session['user_name'])
Пример #19
0
 def post(self):
     args = parser.parse_args()
     password = args.get('password')
     username = args.get('username')
     name = args.get('name')
     logging.debug("sign up {}".format(username))
     people = People.getbyusername(username)
     if people:
         logging.debug("username already taken")
         raise UserAlreadyExistsError
     else:
         people = People.create(name, username)
         people.get().genpass(password)
         user = User.get(username)
         if user is None:
             user = User.get(username)
             logging.warning("User get retry")
         if user is not None:
             login_user(user, remember=True)
         else:
             logging.warning("Still not found")
         return {'id': people.id(), "username": username, "name": name, "admin": False}
Пример #20
0
    def post(self):
        user = User(first_name=self.request.get('first_name'),
                    last_name=self.request.get('last_name'),
                    email=self.request.get('email'),
                    color=self.request.get('color'))

        member = user.put()
        family = load_family_by_email(users.get_current_user().email())
        #adding user to family FamilyMembers
        family.members.append(member)
        #put the Family
        family.put()
        time.sleep(0.1)

        profile_template = the_jinja_env.get_template('templates/profile.html')
        profile_dict = {
            "last_name": user.last_name,
            "first_name": user.first_name,
            "email": user.email,
            "color": user.color,
            "family": family,
        }
        self.response.write(profile_template.render(profile_dict))
Пример #21
0
def authenticate():
    if not has_args(request.form, ['username', 'password']):
        raise InvalidUsage("Bad request. Please use the proper login page.")
    username = request.form['username'].lower()
    # our password is NOT encrypted in transit..
    # we need to implement client slide encryption
    password = request.form['password']
    user = User.login_user(username, password)

    if not user:
        return redirect("./login?login_failed=true", code=302)
    else:
        login_user(user)
        return redirect("./", code=302)
Пример #22
0
def login():
    email = request.form['email']
    passwd = request.form['password']
    print(email, passwd)
    if email == User.admin_email and passwd == User.admin_passwd:
        user = User(email)
        login_user(user)
        flash('Logged in successfully.')
        next = request.args.get('next')
        # is_safe_url should check if the url is safe for redirects.
        # See http://flask.pocoo.org/snippets/62/ for an example.
        if not is_safe_url(next):
            return abort(400)
        return redirect(next or url_for('index'))
    errmsg = "email or password is wrong!"
    return render_template('login.html', email=email, msg=errmsg)
Пример #23
0
    def post(self):
        args = parser.parse_args()
        password = args.get('password')
        username = args.get('username')
        login_status = False
        people = None
        if username and password:
            people = People.getbyusername(username)
            login_status = True if people and people.validpassword(password) else False
            if login_status:
                login_user(User.get(username), remember=True)

        if not login_status:
            raise InvalidLoginError

        return {"username": username, "name": people.name, "position": people.position,"admin": people.admin, "id": people.key.id()}
Пример #24
0
def run(do_debug=False):
    """
	Main function to run the program.
	"""
    # Create the user object which has all of the credentials
    user = User()

    db = MySQLdb.connect(host="134.74.126.107",
                         user=user.username,
                         passwd=user.password,
                         db="F16336team7",
                         cursorclass=MySQLdb.cursors.DictCursor)

    cursor = db.cursor()
    #insert_main(cursor,db,do_debug)
    plot(cursor)
Пример #25
0
 def get(self):
     colors = [
         "Blue", "Brown", "Cyan", "Gold", "Gray", "Green", "Lavendar",
         "Lime", "Magenta", "Navy", "Orange", "Pink", "Purple", "Turquoise",
         "Red", "Yellow"
     ]
     current_user = users.get_current_user()
     user1 = users.get_current_user().email()
     user = User.query().filter(User.email == user1).get()
     family = load_family_by_email(users.get_current_user().email())
     profile_template = the_jinja_env.get_template('templates/profile.html')
     profile_dict = {
         "family": family,
         "last_name": user.last_name,
         "colors": colors,
     }
     self.response.write(profile_template.render(profile_dict))
Пример #26
0
    def get(self):
        colors = [
            "Blue", "Brown", "Cyan", "Gold", "Gray", "Green", "Lavendar",
            "Lime", "Magenta", "Navy", "Orange", "Pink", "Purple", "Turquoise",
            "Red", "Yellow"
        ]
        user_email = users.get_current_user()
        #email=self.request.get

        if user_email:
            signout_link_html = '<a href="%s">sign out</a>' % (
                users.create_logout_url('/'))
            email_address = user_email.email()
            user = User.query().filter(User.email == email_address).get()
            if user:
                self.redirect("/calendar")
            else:
                colors = [
                    "Blue", "Brown", "Cyan", "Gold", "Gray", "Green",
                    "Lavendar", "Lime", "Magenta", "Navy", "Orange", "Pink",
                    "Purple", "Turquoise", "Red", "Yellow"
                ]
                current_user = users.get_current_user()
                # user_color=""
                # for color in colors:
                #     user_color+='<option value="'+color+'">'+color+'</option>'
                self.response.write('''
            Welcome to our site, %s!  Please sign up! <br>
            <form method="post" action="/">
            First Name: <input type="text" name="first_name"> <br>
            Last Name: <input type="text" name="last_name"> <br>
            Color: <select class="" name="color">
            <br> %s <br>
            ''' % (email_address, signout_link_html))
                for color in colors:
                    self.response.write('''
                <option value="%s">%s</option>''' % (color, color))
                self.response.write(
                    '''</select><br><input type="submit"></form>''')

        else:
            login_url = users.create_login_url('/')
            # login_html_element = '<a href="%s">Sign in</a>' % login_url
            # self.response.write('Please log in.<br>' + login_html_element)
            index_template = the_jinja_env.get_template('templates/index.html')
            self.response.write(index_template.render(login=login_url))
Пример #27
0
    def signup(self):
        user_data = json.loads(request.data)
        print(user_data)

        cn = user_data['cn']
        givenName = user_data['givenName']
        sn = user_data['sn']
        telephoneNumber = user_data['telephoneNumber']
        userPassword = user_data['userPassword']
        csr_pem = user_data['userCertificateRequest']

        result = User.try_signup(cn=cn,
                                 givenName=givenName,
                                 sn=sn,
                                 telephoneNumber=telephoneNumber,
                                 userPassword=userPassword,
                                 userCertificateRequest=csr_pem)
        return result
Пример #28
0
    def post(self):
        args = parser.parse_args()
        password = args.get('password')
        username = args.get('username')
        login_status = False
        people = None
        if username and password:
            people = People.getbyusername(username)
            login_status = True if people and people.validpassword(
                password) else False
            if login_status:
                login_user(User.get(username), remember=True)

        if not login_status:
            raise InvalidLoginError

        return {
            "username": username,
            "name": people.name,
            "position": people.position,
            "admin": people.admin,
            "id": people.key.id()
        }
Пример #29
0
from login import User

print("please enter one item  \n1_login\n2signup :")
selection_item = int(input("your selection "))
if selection_item == 1:
    pass
elif selection_item == 2:
    User.register()
else:
    print("invalid")

Пример #30
0
def load_user(username):
    user = User(mongo, username)
    if user.is_authenticated():
        return user
    return None
Пример #31
0
def load_user(user_id):
    return User.get_by_id(user_id, data_base)
Пример #32
0
def callback():
    # Get authorization code Google sent back to you
    code = request.args.get("code")

    # Find out what URL to hit to get tokens that allow you to ask for
    # things on behalf of a user
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send request to get tokens! Yay tokens!
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code,
    )
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens!
    client.parse_request_body_response(json.dumps(token_response.json()))

    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        picture = userinfo_response.json()["picture"]
        users_name = userinfo_response.json()["name"]
        
        if mongoUsr.is_USTHer(users_email):
            # Add user information to Online database
            global user            
            user = logUsr.user_info(
                id_=unique_id, name=users_name, email=users_email, profile_pic=picture
            )
            global profile_pic 
            global first_Name 
            id_ = user.getid()
            name = user.getName()
            email = user.getEmail()
            profile_pic = user.getprofile_pic()
            student_id = get_studentid(email)
            first_Name = name.split(' ', 1)[0]
            
            if not mongoUsr.account_existed(id_):
                mongoUsr.register(id_, name, email, student_id, profile_pic)
                generate_password()
                print('Generated login info!')
                gmail.send(email, get_studentid(email), first_Name)
     
            login_user(user)


            # Create session timeout
            time = timedelta(minutes=60)
            # User will automagically kicked from session after 'time'
            app.permanent_session_lifetime = time
            
            return redirect(url_for('index'))   
        else:
            return redirect(url_for('loginfail'))
Пример #33
0
from login import User
import logging
from colorama import Fore

logging.basicConfig(filename='example.log', level=logging.DEBUG)

while True:
    print(Fore.BLUE + "*-*-*-*-*-*-*-*-*-* WELCOME  *-*-*-*-*-*-*-*-*-*")
    print(Fore.CYAN + "please enter one item  \n1_login \n2_signup ")
    selection_item = int(input("your selection : "))
    if selection_item == 1:
        User.login()
    elif selection_item == 2:
        User.register()
    else:
        print(Fore.LIGHTRED_EX + "invalid choice")
Пример #34
0
def load_family_by_email(email):
    current_user = User.query().filter(User.email == email).fetch()[0]
    family = Family.query(Family.members == current_user.key).fetch()[0]
    return family
Пример #35
0
def load_user(user_id):
    return User.get(user_id)
Пример #36
0
def load_user(user_id):
    return User.get(user_id)