Esempio n. 1
0
def authenticate_user(username: str, password: str):
    user = models.get_user_by_username(username)
    if not user:
        return False
    if not verify_password(password, user.hashed_password):
        return False
    return user
Esempio n. 2
0
    def post(self):
        send_to_username = self.request.get('username')
        target_user = models.get_user_by_username(send_to_username)

        # how to send an email?
        user = models.get_current_user()
        if (user):
            message = mail.EmailMessage(
                sender=user.email,
                subject="Message via WorkWithMe from " + user.username)

            message.to = target_user.email  #"Albert Johnson <*****@*****.**>"
            message.body = self.request.get('message')

            m = models.CMessage(parent=user,
                                user_to=target_user,
                                content=message.body)
            m.put()

            message.send()

            logging.info("sender: " + message.sender)
            logging.info("subject: " + message.subject)
            logging.info("to: " + message.to)
            logging.info("body: " + message.body)

            self.response.out.write("OK")
        else:
            self.response.out.write("User Not Logged In")
Esempio n. 3
0
    def get(self, username):
        events = []
        old_events = []
        user_to_view = None
        user_is_me = False

        #decode username from params
        username = username.replace("%20", " ")
        self.FirstInit()
        logging.info("username: " + username)
        user_to_view = models.get_user_by_username(username)
        if user_to_view:
            events = user_to_view.get_events(False)

            user = models.get_current_user()
            if user and user_to_view.user_id() == user.user_id():
                user_is_me = True
                old_events = user_to_view.get_events(
                    True
                )  # Security - don't let people see each other's histories

        template_values = {
            'user_to_view': user_to_view,
            'events': events,
            'old_events': old_events,
            'user_is_me': user_is_me
        }
        self.AddUserInfo(template_values)
        path = os.path.join(os.path.dirname(__file__), 'templates/user.htm')
        self.response.out.write(template.render(path, template_values))
Esempio n. 4
0
	def get(self, username):
		user = models.get_user_by_username(username)
		if user:
			questions = models.get_recent_questions()
			variables = {'user': user,
				'questions': questions }
			self.render_template(**variables)
		else:
			variables = { 'message': 'Usuário não encontrado'.decode('utf-8') }
			self.render_template('fail', **variables)
Esempio n. 5
0
	def get_user(self):
		userlogin = self.request.cookies.get('userlogin', None)
		if userlogin:
			user = models.get_user_by_username(userlogin)
			if not user:
				self.response.set_cookie('userlogin', '', max_age=0,
					overwrite=True)
			return user
		else:
			return None
Esempio n. 6
0
async def get_user_by_username(username: str,
                               current_user: User = Depends(get_current_user)):
    if not current_user.superuser and username != current_user.username:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail='Insufficient rights to resource')
    if username != current_user.username:
        user = models.get_user_by_username(username)
    else:
        user = current_user
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail='User not found')
    return user
Esempio n. 7
0
	def post(self):
		username = cgi.escape(self.request.get("username"))
		password = cgi.escape(self.request.get("password"))
		referer_val = self.request.get('referer_val')
		user = models.get_user_by_username(username)

		if user and valid_pw(username, password, user.password):
			cookie_val = make_secure_val(str(user.key().id()))
			self.response.headers.add_header('Set-Cookie', 'user_id=%s; Path=/' % str(cookie_val))
			self.redirect(referer_val)
		else:
			login_error = "Invalid login"
			self.render_login(referer_val, login_error)
Esempio n. 8
0
    def post(self, username, action):
        if action == "closeout":
            user = models.get_current_user()
            target_user = models.get_user_by_username(username)
            if user.user_id() != target_user.user_id():
                self.response.out.write("You ain't got no right!")
                return False

            if user:
                events = models.Event.all().ancestor(target_user).filter(
                    "when_end >=", datetime.now(tz)).fetch(50)
                for event in events:
                    event.when_end = datetime.now(tz)
                    event.put()
        self.redirect("/user/" + username)
Esempio n. 9
0
    def post(self):
        user = models.get_current_user()
        un = self.request.get("username")

        existing_user = models.get_user_by_username(un)
        if existing_user and (existing_user.user_id() != user.user_id()):
            self.response.out.write('A user with this username already exists')
            return

        user.username = un
        user.put()

        output = simplejson.dumps([user.username, "UpdateComplete"])

        self.response.out.write(output)
Esempio n. 10
0
    def login():
        if request.method == 'GET':
            return render_template('login.html')
        username = request.form['username']
        password = request.form['password']

        remember_me = False
        if 'remember_me' in request.form:
            remember_me = True

        user = get_user_by_username(username)

        if user is None or not user.password_ok(password):
            return redirect(url_for('login'))
        login_user(user, remember=remember_me)
        return redirect(request.args.get('next') or url_for('trips'))
Esempio n. 11
0
async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail='Could not validate credentials',
        headers={'WWW-Authenticate': 'Bearer'})
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get('sub')
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    user = models.get_user_by_username(username=username)
    if user is None:
        raise credentials_exception
    return user
Esempio n. 12
0
	def get(self, *args, **kwargs):
		if args[0].startswith('tag:'):
			tag = args[0].split(':')[1]
			questions = models.get_questions_by_tag(tag)
			variables = { 'user': self.get_user(),
				'questions': questions }
			self.render_template(**variables)
		else:
			username = args[0]
			user = models.get_user_by_username(username)
			if user:
				questions = models.get_questions_by_user(user)
				variables = { 'user': user,
					'questions': questions }
				self.render_template(**variables)
			else:
				variables = { 'message': 'Usuário não encontrado'.decode('utf-8') }
				self.render_template('fail', **variables)
Esempio n. 13
0
def userline(request, username):
    try:
        user = models.get_user_by_username(username)
    except models.DatabaseError:
        raise Http404

    # Query for the reading users ids
    reading_usernames = []
    if request.user['is_authenticated']:
        reading_usernames = models.get_reading_usernames(username) + [username]

    # Adds a property on the user to indicate whether the currently
    # logged in user is reading some user
    is_reading = username in reading_usernames

    if request.user['is_authenticated'] and request.method == "POST":
        if user['reading']:
            models.unread(request.session['username'], username)
        else:
            models.read(request.session['username'], username)

        return HttpResponseRedirect(reverse('userline'))

    start = request.GET.get('start')

    mikis, next_timeuuid = models.get_userline(username,
                                               start=start,
                                               limit=NUM_PER_PAGE)

    #profile = models.get_profile(username)

    context = {
        'user': user,
        'username': username,
        #'profile': profile,
        'mikis': mikis,
        'next': next_timeuuid,
        'is_reading': is_reading,
        'reading_usernames': reading_usernames,
    }
    return render_to_response('userline.html',
                              context,
                              context_instance=RequestContext(request))
Esempio n. 14
0
	def post(self):
		username = cgi.escape(self.request.get("username"))
		password = cgi.escape(self.request.get("password"))
		verify = cgi.escape(self.request.get("verify"))
		email = cgi.escape(self.request.get("email"))

		username_error = ""
		pwd_error = ""
		pwd_verify_error = ""
		email_error = ""

		if not valid_username(username):
			username_error = "That's not a valid username."

		if not valid_password(password):
			pwd_error = "That wasn't a valid password."
		elif verify != password:
			pwd_verify_error = "Your passwords didn't match."
		else:
			user = models.get_user_by_username(username)
			if user:
				username_error = "That user already exists."
				username = ""

		if email and (not valid_email(email)):
			email_error = "That's not a valid email."


		if (username_error or pwd_error or pwd_verify_error or email_error):
			self.render_signup(username, email, username_error, pwd_error, pwd_verify_error, email_error)
		else:
			pwd_hash = make_pw_hash(username, password)
			user = models.set_user(username, pwd_hash, email)
			
			cookie_val = make_secure_val(str(user.key().id()))
			self.response.headers.add_header('Set-Cookie', 'user_id=%s; Path=/' % cookie_val)
			referer_val = self.request.get('referer_val')
			if referer_val:
				self.redirect(referer_val)
			else:
				self.redirect("/")
Esempio n. 15
0
def userline(request, username):
    try:
        user = models.get_user_by_username(username)
    except models.DatabaseError:
        raise Http404

    # Query for the reading users ids
    reading_usernames = []
    if request.user['is_authenticated']:
        reading_usernames = models.get_reading_usernames(username) + [username]

    # Adds a property on the user to indicate whether the currently
    # logged in user is reading some user
    is_reading = username in reading_usernames

    if request.user['is_authenticated'] and request.method == "POST":
        if user['reading']:
            models.unread(request.session['username'], username)
        else:
            models.read(request.session['username'], username)

        return HttpResponseRedirect(reverse('userline'))


    start = request.GET.get('start')

    mikis, next_timeuuid = models.get_userline(username, start=start, limit=NUM_PER_PAGE)

    #profile = models.get_profile(username)

    context = {
        'user': user,
        'username': username,
        #'profile': profile,
        'mikis': mikis,
        'next': next_timeuuid,
        'is_reading': is_reading,
        'reading_usernames': reading_usernames,
    }
    return render_to_response('userline.html', context,
        context_instance=RequestContext(request))
Esempio n. 16
0
    def get(self, username):
        user_to_view = None
        user_is_me = False

        user_to_view = models.get_user_by_username(username)
        if user_to_view:
            events = user_to_view.get_events(False)
            old_events = user_to_view.get_events(True)

            user = models.get_current_user()
            if user and user_to_view.user_id() == user.user_id():
                user_is_me = True

        template_values = {
            'user_to_view': user_to_view,
            'user_is_me': user_is_me
        }
        self.AddUserInfo(template_values)
        path = os.path.join(os.path.dirname(__file__),
                            'templates/conversation.htm')
        self.response.out.write(template.render(path, template_values))
Esempio n. 17
0
def verify_password(_login, password):
    """
    Verification of password

    :param _login:
    :param password:
    :return bool:
    """
    # Try to see if it's a token first
    user_id = User.verify_auth_token(_login)
    if user_id:
        user = get_user_by_id(user_id)
    else:
        user = get_user_by_email(_login)
        if not user:
            user = get_user_by_username(_login)
            if not user or not user.verify_password(password):
                return False
        else:
            if not user.verify_password(password):
                return False
    g.user = user
    return True