예제 #1
0
  def setUp( self ):
    Test_controller.setUp( self )

    self.notebook = Notebook.create( self.database.next_id( Notebook ), u"my notebook", trash_id = u"foo" )
    self.database.save( self.notebook )

    self.anon_notebook = Notebook.create( self.database.next_id( Notebook ), u"Luminotes" )
    self.database.save( self.anon_notebook )
    self.anon_note = Note.create(
      self.database.next_id( Note ), u"<h3>my note</h3>",
      notebook_id = self.anon_notebook.object_id,
    )
    self.database.save( self.anon_note )

    self.login_note = Note.create(
      self.database.next_id( Note ), u"<h3>login</h3>",
      notebook_id = self.anon_notebook.object_id,
    )
    self.database.save( self.login_note )

    self.blog_notebook = Notebook.create( self.database.next_id( Notebook ), u"Luminotes blog" )
    self.database.save( self.blog_notebook )
    self.blog_note = Note.create(
      self.database.next_id( Note ), u"<h3>my blog entry</h3>",
      notebook_id = self.blog_notebook.object_id,
    )
    self.database.save( self.blog_note )

    self.guide_notebook = Notebook.create( self.database.next_id( Notebook ), u"Luminotes user guide" )
    self.database.save( self.guide_notebook )
    self.guide_note = Note.create(
      self.database.next_id( Note ), u"<h3>it's all self-explanatory</h3>",
      notebook_id = self.guide_notebook.object_id,
    )
    self.database.save( self.guide_note )

    self.privacy_notebook = Notebook.create( self.database.next_id( Notebook ), u"Luminotes privacy policy" )
    self.database.save( self.privacy_notebook )
    self.privacy_note = Note.create(
      self.database.next_id( Note ), u"<h3>yay privacy</h3>",
      notebook_id = self.privacy_notebook.object_id,
    )
    self.database.save( self.privacy_note )

    self.username = u"mulder"
    self.password = u"trustno1"
    self.email_address = u"*****@*****.**"
    self.user = None
    self.session_id = None

    self.user = User.create( self.database.next_id( User ), self.username, self.password, self.email_address )
    self.database.save( self.user )
    self.database.execute( self.user.sql_save_notebook( self.notebook.object_id ) )

    self.anonymous = User.create( self.database.next_id( User ), u"anonymous" )
    self.database.save( self.anonymous )
    self.database.execute( self.anonymous.sql_save_notebook( self.anon_notebook.object_id, read_write = False, owner = False, rank = 0 ) )
    self.database.execute( self.anonymous.sql_save_notebook( self.blog_notebook.object_id, read_write = False, owner = False, rank = 1 ) )
    self.database.execute( self.anonymous.sql_save_notebook( self.guide_notebook.object_id, read_write = False, owner = False, rank = 2 ) )
    self.database.execute( self.anonymous.sql_save_notebook( self.privacy_notebook.object_id, read_write = False, owner = False, rank = 3 ) )
예제 #2
0
    def post(self):
        validcode = self.get_request("validcode", "")
        if "validcode" in self.session:
            if validcode != self.session['validcode'] :
                self.print_result(False, "ValidCode is incorrect!!")
                return
        else:
            self.print_result(False, "ValidCode is incorrect!!")
            return
        user = User().getByID(self.userID, False)
        if  user :
            # found it
            # send email
            activationKey = user.getEncodeStr(str(user.user_login)+"-"+ str(time.time()))
            user.user_activation_key = activationKey
            if user.update() :
                self.print_result(True, "Done")
                """
                    Send Email to register
                """
                msg = self.render_string("email/register.html",activationKey=activationKey, login_user = user.user_login, website_url= self.webroot_url("", True), web_title = self.web_title() )
                subject = "["+self.web_title()+"] ReSend Activation Key"
                qm = SingleMail.get_instance()
                qm.send_email(user.user_email,subject, msg, 'html')

            else :
                self.print_result(False, "Failed to Update DB")

        else:
            # find failed
            self.print_result(False, "Can not find any record")
예제 #3
0
  def setUp( self ):
    Test_controller.setUp( self )
    Groups.urllib2 = Stub_urllib2

    self.group_name = u"my group"
    self.group_name2 = u"other group"
    self.username = u"mulder"
    self.password = u"trustno1"
    self.email_address = u"*****@*****.**"
    self.username2 = u"scully"
    self.password2 = u"trustsome1"
    self.email_address2 = u"*****@*****.**"
    self.username3 = u"skinner"
    self.password3 = u"trustne1"
    self.email_address3 = u"*****@*****.**"

    self.group = Group.create( self.database.next_id( Group ), self.group_name )
    self.database.save( self.group, commit = False )

    self.group2 = Group.create( self.database.next_id( Group ), self.group_name )
    self.database.save( self.group2, commit = False )

    self.user = User.create( self.database.next_id( User ), self.username, self.password, self.email_address )
    self.database.save( self.user, commit = False )
    self.database.execute( self.user.sql_save_group( self.group.object_id, admin = False ) )

    self.user2 = User.create( self.database.next_id( User ), self.username2, self.password2, self.email_address2 )
    self.database.save( self.user2, commit = False )
    self.database.execute( self.user2.sql_save_group( self.group.object_id, admin = True ) )

    self.user3 = User.create( self.database.next_id( User ), self.username3, self.password3, self.email_address3 )
    self.database.save( self.user3, commit = False )
    self.database.execute( self.user3.sql_save_group( self.group.object_id, admin = False ) )

    self.database.commit()
예제 #4
0
 def post(self):
     username = self.request.get('username')
     password = self.request.get('password')
     usr = User(username)
     if usr.key and usr.validate_pw(password):
         self.set_user_cookie(username)
         self.redirect("/")
         return None
     self.formpost(username, "Wrong Username or Password")
예제 #5
0
 def GetUserId(self):
     
     if endpoints.get_current_user() == None:
         raise endpoints.UnauthorizedException("Must log in")
     
     user = User.query(User.username == endpoints.get_current_user().email()).get()
     if user == None:
         user = User(username = endpoints.get_current_user().email())
         user.put()
     return user.key
예제 #6
0
class RemoveHandler(tornado.web.RequestHandler):
    def initialize(self, mysql_handler, LOG):
        self.mysql_handler = mysql_handler
        self.LOG = LOG
        self.user = User(mysql_handler, LOG)
        self.device = Device(mysql_handler, LOG)
        self.favorite = Favorite(mysql_handler, LOG)
        self.rsp_handler = CommResponse()
        return

    def post(self):
        self.LOG.debug('this is %s' % self.__class__.__name__)
        try:
            request_json = json.loads(self.request.body)
            user_phone = request_json['user_phone']
            user_login_mobile_uuid = request_json['user_login_mobile_uuid']
            collection_type = request_json['collection_type']
            collection_name = request_json['collection_name']
        except Exception as e:
            self.LOG.error('parameters error.')
            self.rsp_msg = self.rsp_handler.generate_rsp_msg('21001', None)
            self.write(self.rsp_msg)
            return

        if not self.user.check_login_status(user_phone, user_login_mobile_uuid):
            self.LOG.error('user [%s] not login.' % user_phone)
            self.mysql_handler.rollback_db()
            self.rsp_msg = self.rsp_handler.generate_rsp_msg('21006', None)
            self.write(self.rsp_msg)
            return

        (ret, num) = self.favorite.remove_collection(user_phone, collection_name, collection_type)
        if not ret:
            self.LOG.error('delete collection from mysql failed.')
            self.rsp_msg = self.rsp_handler.generate_rsp_msg('21999', None)
            self.mysql_handler.rollback_db()
            self.write(self.rsp_msg)
            return

        if num:
            modify_info = {
                'collected': 'collected - 1'
            }
            if collection_type == 'user':
                self.user.modify_user(collection_name, modify_info)
            elif collection_type == 'device':
                self.device.modify_device(collection_name, modify_info)
        
        self.rsp_msg = self.rsp_handler.generate_rsp_msg('200', None)
        self.mysql_handler.commit_db()
        self.write(self.rsp_msg)
        return
예제 #7
0
 def get(self):
     tid = self.get_request("id", "")
     user = None
     if (id != ""):
         user = User().getByActivateToken(tid, False)
     success = False
     login = ""
     if not user is None:
         user.user_status = 1
         user.user_activation_key = ""
         login = user.user_login
         if user.update():
             success = True
     self.render("public/activate_account.html", login_name=login, title="Activate Account", isSuccess=success)
예제 #8
0
    def get(self):

        user = users.get_current_user()
        #checks to see if we have a user signed in
        if user:
            userProfile = User.getByEmail(user.email())
            #if user profile is empty create one
            if not userProfile:
                userProfile = User()
                userProfile.email = user.email()
                userProfile.nickname = 'Anonymous'
                userProfile.score = 0
                userProfile.played = 0
                userProfile.put()

            template_values = {
                'user': userProfile
            }

            template = jinja_environment.get_template('profile.html')
            self.response.out.write(template.render(template_values))
        #if not is ask them to sign in
        else:
            template_values = {
                'signinurl' : users.create_login_url("/")
            }

            template = jinja_environment.get_template('signin.html')
            self.response.out.write(template.render(template_values))
예제 #9
0
def test_db():
    # INSERT
    if not session.query(exists().where(User.email == '*****@*****.**')).scalar():
        u1 = User()
        u1.name = "Test user"
        u1.email = "*****@*****.**"

        a1 = Address()
        a1.street = "Str 123"
        a1.city = "City WTF"

        u1.address = a1
        session.add(a1)
        session.add(u1)
        session.commit()

    # check if record exists in db:
    # print session.query(Address).filter_by(city='City WTF').count()
    # print bool( session.query(Address).filter_by(city='City WTF').count() )

    #   SELECT
    if session.query(exists().where(Address.city == 'City WTF')).scalar():
        a2 = session.query(Address).filter_by(city='City WTF').first()
        print a2.city

    if bool(session.query(Address).filter_by(city='City WTF').count()):
        a2 = session.query(Address).filter_by(city='City WTF').first()
        print a2.city


    # UPDATE
    if session.query(exists().where(User.email == '*****@*****.**')).scalar():
        session.query(User).filter_by(email='*****@*****.**').update({"nick": "a"})
        session.commit()

    if session.query(exists().where(User.email == '*****@*****.**')).scalar():
        u = session.query(User).filter_by(email='*****@*****.**').first()
        u.nick = "b"
        session.commit()


    # DELETE
    if session.query(exists().where(User.email == '*****@*****.**')).scalar():
        session.query(User).filter_by(email='*****@*****.**').delete()
        session.commit()

    if session.query(exists().where(Address.city == 'City WTF')).scalar():
        session.query(Address).filter_by(city='City WTF').delete()
        session.commit()
예제 #10
0
 def post(self):
     user_account = self.get_request("account","")
     email = self.get_request("email", "")
     user_url = self.get_request("personal_url", "")
     displayName = self.get_request("display_name", "")
     password = self.get_request("password", "")
     role = self.get_request("role","")
     status = self.get_int_request("status",0)
     if user_account == "":
         self.print_result(False, "User Account Cannot be blank!")
         return
     if user_url != "":
         tmp = user_url.lower()
         if not tmp.startswith("http"):
             user_url = "http://"+user_url
         if not pyUtility.isURL(user_url):
             self.print_result(False, "The Format of URL is wrong!")
             return
     if email == "":
         self.print_result(False, "Email Cannot be blank!")
         return
     if not pyUtility.isEmail(email):
         self.print_result(False, "Email Format is incorrect!")
         return
     if password == "":
         self.print_result(False, "Password is empty!")
         return
     user_account = user_account.lower()
     email = email.lower()
     if not pyUtility.isAccountLegal(user_account):
         self.print_result(False, "The Format of Account is not legal")
         return
     if not User().isUnique(email=email, acc=user_account):
         self.print_result(False, "Account or Email Has been used")
         return
     user = User()
     newPwd = user.getEncodeStr(password)
     user.user_login = user_account
     user.user_pass = newPwd
     user.user_email = email
     user.user_url = user_url
     user.role = role
     user.user_status = status
     user.display_name = displayName
     newID = user.save()
     if newID >0:
         self.print_result(True, "Done", self.get_webroot_url()+"admin/users/")
     else:
         self.print_result(False, "Failed to Add Account to DB")
예제 #11
0
 def post(self):
     loggedIn = True
     username = self.request.get('username')
     password = self.request.get('password')
     android = self.request.get('android')
     use = User.all().filter('username', username)
     self.session.delete(username)
예제 #12
0
파일: Auth.py 프로젝트: wj844908240/my_pro
def register():
    if not request.json:
        resultDict = returnNoneMsg("failed!")
        return jsonify(resultDict)
    jsonData = request.get_data()
    dataDict = json.loads(jsonData)
    name = dataDict.get('name', None)
    password = dataDict.get('password', None)
    email = dataDict.get('email', None)
    phone = dataDict.get('phone', None)

    user_info = User.query.filter_by(user_name=name).first()
    if user_info:
        resultDict = returnNoneMsg(cec.code_1)
        return jsonify(resultDict)

    user = User(user_name=name,
                email=email,
                phone=phone,
                user_password=generate_password_hash(password),
                user_reg_ip=request.remote_addr)
    db.session.add(user)
    db.session.commit()

    resultDict = returnMsg("register success")
    return jsonify(resultDict)
예제 #13
0
class Topic:

    title = ""
    categorie = ""
    user = User("","","")

    def __init__(self, title, categorie, user):
        self.title = title
        self.categorie = categorie
        self.user = user

    @staticmethod
    def listeTitreTopic():
        return bdd.listeTitreTopic()

    @staticmethod
    def creationTopic(title, idCategory, idUser):
        return bdd.creationTopic(title, idCategory, idUser)

    @staticmethod
    def supressionTopic(idTopic):
        return bdd.supressionTopic(idTopic)

    @staticmethod
    def miseAjourTopic(idTopic, title):
        return bdd.miseAjourTopic(idTopic,title)
예제 #14
0
    def post(self):
        data = json.loads(self.request.body.decode("utf-8"))
        user = User(data['first_name'], data['last_name'], data['password'],
                    data['email'], data['phone'], [])

        self.__users_repo.create(user)
        self.set_status(201)
예제 #15
0
  def setUp( self ):
    self.database = Database(
      Connection_wrapper( sqlite.connect( ":memory:", detect_types = sqlite.PARSE_DECLTYPES, check_same_thread = False ) ),
      cache = Stub_cache(),
    )
    self.database.execute_script( file( "model/schema.sqlite" ).read(), commit = True )

    self.username = u"mulder"
    self.password = u"trustno1"
    self.email_address = u"*****@*****.**"
    self.user = User.create( self.database.next_id( User ), self.username, self.password, self.email_address )
    self.database.save( self.user, commit = False )

    self.trash = Notebook.create( self.database.next_id( Notebook ), u"trash" )
    self.database.save( self.trash, commit = False )
    self.notebook = Notebook.create( self.database.next_id( Notebook ), u"notebook", self.trash.object_id, user_id = self.user.object_id )
    self.database.save( self.notebook, commit = False )

    note_id = self.database.next_id( Note )
    self.note1 = Note.create( note_id, u"<h3>my title</h3>blah", notebook_id = self.notebook.object_id, startup = True, user_id = self.user.object_id )
    self.database.save( self.note1, commit = False )

    note_id = self.database.next_id( Note )
    self.note2 = Note.create( note_id, u"<h3>other title</h3>whee", notebook_id = self.notebook.object_id, user_id = self.user.object_id )
    self.database.save( self.note2, commit = False )
예제 #16
0
 def initialize(self, mysql_handler, LOG):
     super(UserHandler, self).initialize()
     self.mysql_handler = mysql_handler
     self.LOG = LOG
     self.user = User(mysql_handler, LOG)
     self.rsp_handler = CommResponse()
     return
예제 #17
0
 def initialize(self, mysql_handler, redis_handler, LOG):
     self.mysql_handler = mysql_handler
     self.redis_handler = redis_handler
     self.LOG = LOG
     self.user = User(mysql_handler, LOG)
     self.picture = Picture(mysql_handler, LOG)
     return
예제 #18
0
class UserHandler(tornado.web.RequestHandler):
    def initialize(self, mysql_handler, redis_handler, LOG):
        self.mysql_handler = mysql_handler
        self.redis_handler = redis_handler
        self.LOG = LOG
        self.user = User(mysql_handler, LOG)
        self.picture = Picture(mysql_handler, LOG)
        return
    def get_self_info(self, user_phone):
        user_info = self.user.check_user_exist(user_phone)
        if user_info:
            image_info = self.picture.get_image_by_phone(user_phone, 'user')
            try:
                image_big_mame = image_info['pic_big_name']
                image_sml_mame = image_info['pic_sml_name']
            except:
                image_big_mame = None
                image_sml_mame = None
            
            user_info['pic_big_name'] = image_big_mame
            user_info['pic_sml_name'] = image_sml_mame
            #del user_info['login_status']

            image_info = self.picture.get_image_by_phone(user_phone, 'license')
            try:
                image_big_mame = image_info['pic_big_name']
                image_sml_mame = image_info['pic_sml_name']
            except:
                image_big_mame = None
                image_sml_mame = None
            user_info['license_big_name'] = image_big_mame
            user_info['license_sml_name'] = image_sml_mame
        return user_info
예제 #19
0
 def add(self, user: User):
     if not self.user_exists(user):
         self.db.insert(user.__dict__)
         addedUser = self.get_by_id(user.email)
         return User(addedUser['email'], addedUser['username'])
     else:
         raise Exception("User with email: " + user.email + " already exists")
예제 #20
0
 def initialize(self, mysql_handler, LOG):
     self.mysql_handler = mysql_handler
     self.LOG = LOG
     self.user = User(mysql_handler, LOG)
     self.order = Order(mysql_handler, LOG)
     self.rsp_handler = CommResponse()
     return
예제 #21
0
    def index(self):
        user_model = User()
        category_model = Category()
        product_model = Product()

        users = user_model.get_total_users()
        categories = category_model.get_total_categories()
        products = product_model.get_total_products()

        last_products = product_model.get_last_products()

        return self.render('home_admin.html',report={
           'users':0 if not users else users[0],
            'categories':0 if not categories else categories[0],
            'products':0 if not products else products[0]
        },last_products=last_products)
예제 #22
0
파일: logout.py 프로젝트: aquafemi/Jirga
 def post(self):
     loggedIn= True
     username=self.request.get('username')
     password=self.request.get('password')
     android=self.request.get('android')
     use = User.all().filter('username',username)
     self.session.delete(username)
예제 #23
0
파일: jsonLogin.py 프로젝트: aquafemi/Jirga
 def post(self):
     loggedIn= False
     username=self.request.headers.get('Username')
     password=self.request.headers.get('Password')
     print("username="******"password="******"match")
             i = uuid.uuid1()
             sess = Session(user=user.username,sessId=str(i))
             sess.put()
             self.response.headers['Content-Type'] = 'application/json'
             obj = {
                 'sessKey':str(i)
             }
             self.response.out.write(json.dumps(obj))
         else:
             #no user found/something went wrong
             print("badpass")
     else:
         print("badname")
예제 #24
0
    def post(self, level_id):
        user = User.getLevelBlockUser(users.get_current_user())

        if user:
            level = self.request.get('level')
            name = self.request.get('name')
            if level_id:
                l = Level.getById(int(level_id))
                #only modify if you are the original author
                if l.user.id == user.key.id:
                    l.name = name
                    l.user = user.key
                    l.score = 0
                    l.published = False
                    l.level = str(level)
                    l.put()
            else:
                l = Level()
                l.name = name
                l.user = user.key
                l.score = 0
                l.published = False
                l.level = str(level)
                l.put()

            self.response.out.write(level)

        else:
            template_values = {
                'signinurl': users.create_login_url("/")
            }

            template = jinja_environment.get_template('signin.html')
            self.response.out.write(template.render(template_values))
예제 #25
0
 def get(self,jirgaId):
     loggedIn= False
     user = self.getuser()
     if(user is not None):
         jirga = Jirga.all().filter('jirgaId', jirgaId).get()
         public = jirga.publicJirga
         if(public == 0):
             #private jirga
             template_params = {
                 'public':public,
             }
         else:
             #public
             if(user in jirga.members):
                 #user is a member
                 member = 1
             else:
                 #user is not a member
                 member = 0
             template_params = {
                 'public':public,
                 'member':member
             }
         member = User.get(jirga.members)
         obj2={'members':member}
         template_params.update(obj2)
         template_params.update({'user':user})
         template_params.update({'jirga':jirga})
         render_template(self,"jirgaSettings.html",template_params)
     else:
         self.response.write("FAIL - you need to be logged in for this")
예제 #26
0
 def post(self):
     loggedIn= False
     username=self.request.get('username')
     password=self.request.get('password')
     use = User.all().filter('username',username)
     if use.count() == 1:
         #user found
         user = use.get()
         if(user.password == password):
             i = uuid.uuid1()
             sess = Session(user=user.username,sessId=str(i))
             sess.put()
             self.session['sessId']=str(i)
             loggedIn = True
             template_params={'loggedIn':loggedIn,
                             'user': user.username}
             render_template(self,'login.html',template_params)
         else:
             #no user found/something went wrong
             loginError = True
             template_params={
                 'loggedIn': loggedIn,
                 'loginError': loginError,
             }
             render_template(self,'login.html',template_params)
     else:
         #no user found/something went wrong
         loginError = True
         template_params={
             'loggedIn': loggedIn,
             'loginError': loginError,
         }
         render_template(self,'login.html',template_params)
예제 #27
0
  def create_thread( self, user_id ):
    """
    Create a new forum thread with a blank post, and give the thread a default name. Then redirect
    to that new thread.

    @type user_id: unicode or NoneType
    @param user_id: id of current logged-in user (if any)
    @rtype dict
    @return { 'redirect': new_notebook_url }
    @raise Access_error: the current user doesn't have access to create a post
    @raise Validation_error: one of the arguments is invalid
    """
    if user_id is None:
      raise Access_error()

    user = self.__database.load( User, user_id )
    if user is None or not user.username or user.username == "anonymous":
      raise Access_error()

    anonymous = self.__database.select_one( User, User.sql_load_by_username( u"anonymous" ), use_cache = True )
    if anonymous is None:
      raise Access_error()

    # for now, crappy hard-coding to prevent just anyone from creating a blog thread
    if self.__name == u"blog" and user.username != u"witten":
      raise Access_error()

    # create the new notebook thread
    thread_id = self.__database.next_id( Notebook, commit = False )
    thread = Notebook.create( thread_id, self.DEFAULT_THREAD_NAME, user_id = user.object_id )
    self.__database.save( thread, commit = False )

    # associate the forum tag with the new notebook thread
    tag = self.__database.select_one( Tag, Tag.sql_load_by_name( u"forum", user_id = anonymous.object_id ) )
    self.__database.execute(
      anonymous.sql_save_notebook_tag( thread_id, tag.object_id, value = self.__name ),
      commit = False,
    )

    # give the anonymous user access to the new notebook thread
    self.__database.execute(
      anonymous.sql_save_notebook( thread_id, read_write = True, owner = False, own_notes_only = True ),
      commit = False,
    )

    # create a blank post in which the user can  start off the thread
    note_id = self.__database.next_id( Notebook, commit = False )
    note = Note.create( note_id, u"<h3>", notebook_id = thread_id, startup = True, rank = 0, user_id = user_id )
    self.__database.save( note, commit = False )

    self.__database.commit()

    if self.__name == "blog":
      return dict(
        redirect = u"/blog/%s" % thread_id,
      )

    return dict(
      redirect = u"/forums/%s/%s" % ( self.__name, thread_id ),
    )
예제 #28
0
    def post(self, levelid=""):
        user = User.getLevelBlockUser(users.get_current_user())
        currentlevel = Level.getById(int(levelid))
        action = self.request.get('done')
        if user:
            if action == 'true':
                self.response.headers['Content-Type'] = 'application/json'
                #check to see if level belongs to user and is if published
                if currentlevel.user.id == user.key.id:
                    if not currentlevel.published:
                        currentlevel.published = True
                        currentlevel.played += 1
                        currentlevel.put()
                    else:
                        user.score += 1
                        user.put()
                    self.response.out.write('{"points": 1, "publish": true}')
                else:
                    score = 0
                    if currentlevel.jackpot:
                        score = math.ceil(currentlevel.score * 0.5)
                        creator = User.get_by_id(currentlevel.user.id())
                        creator.score += int(score)
                        creator.put()
                        currentlevel.jackpot = False
                        currentlevel.played += 1
                        currentlevel.put()
                    else:
                        score += math.ceil(currentlevel.score * 0.1)
                    user.score += int(score)
                    user.put()
                    self.response.out.write('{"points": ' + str(score) + ', "publish": false}')
            else:
                if currentlevel.published:
                    if currentlevel.jackpot:
                        currentlevel.score += 1

                    currentlevel.played += 1
                    currentlevel.put()

        else:
            template_values = {
                'signinurl' : users.create_login_url("/")
            }

            template = jinja_environment.get_template('signin.html')
            self.response.out.write(template.render(template_values))
예제 #29
0
 def logOut(self, currentSession):
     try:
         user = User.get(User.currentSession == currentSession)
         user.currentSession = ""
         user.save()
         return True
     except peewee.DoesNotExist:
         return False
예제 #30
0
 def isMyRoleAdmin(self, currentSession):
     try:
         user = User.get(User.currentSession == currentSession)
         if user.role == "admin":
             return True
         return False
     except peewee.DoesNotExist:
         return False
예제 #31
0
 def post(self):
     user = users.get_current_user()
     #checks to see if we have a user signed in
     if user:
         userProfile = User.getByEmail(user.email())
         #if user profile is empty create one
         userProfile.nickname = self.request.get("nickname")
         userProfile.put()
예제 #32
0
파일: auth_routes.py 프로젝트: Timuer/BBS
def register_post():
    form = request.form
    is_success, messages = User.register(form)
    if is_success:
        return redirect(url_for(".login"))
    else:
        token = generate_token()
        return render_template("register.html", token=token, messages=messages)
예제 #33
0
 def initialize(self, mysql_handler, LOG):
     self.mysql_handler = mysql_handler
     self.LOG = LOG
     self.user = User(mysql_handler, LOG)
     self.device = Device(mysql_handler, LOG)
     self.favorite = Favorite(mysql_handler, LOG)
     self.rsp_handler = CommResponse()
     return
예제 #34
0
def admin_users(request):
    """
	增加一个路由 /admin/users
	只有 id 为 1 的用户可以访问这个页面, 其他用户访问会定向到 /login
	这个页面显示了所有的用户 包括 id username password
	"""
    body = template('admin_users.html', user_list=User.all())
    return http_response(body)
예제 #35
0
def getEmail():
    try:
        user = User.get(
            User.currentSession == request.cookies.get('currentSession'))
        # print(user)
        return user.email
    except peewee.DoesNotExist:
        return ""
예제 #36
0
def setCurrentSession(currentSession, email):
    currentUser = User.get(User.email == email)
    if currentSession == "":
        currentUser.currentSession = ""
        currentUser.save()
    else:
        currentUser.currentSession = currentSession
        currentUser.save()
예제 #37
0
 def getuser(self):
     if self.session.get('sessId'):
         i = str(self.session.get('sessId'))
         sess = Session.all().filter('sessId',i).get()
         user = User.all().filter('username',sess.user).get()
         return user
     else:
         return None
예제 #38
0
  def create_anonymous_user( self ):
    # create the anonymous user
    anonymous_user_id = self.database.next_id( User )
    self.anonymous = User.create( anonymous_user_id, u"anonymous", None, None )
    self.database.save( self.anonymous, commit = False )

    # give the anonymous user read-only access to the main notebook
    self.database.execute( self.anonymous.sql_save_notebook( self.main_notebook.object_id, read_write = False, owner = False ), commit = False )
예제 #39
0
 def _get_user(self, user_id, cursor):
     command = 'SELECT * FROM `frc_library`.`user` WHERE `user_id` = %s;'
     cursor.execute(command, user_id)
     result = cursor.fetchone()
     if result:
         return User(user_id, result[0], result[2])
     else:
         return None
예제 #40
0
  def setUp( self ):
    self.object_id = u"17"
    self.username = u"bob"
    self.password = u"foobar"
    self.email_address = u"*****@*****.**"
    self.delta = timedelta( seconds = 1 )

    self.user = User.create( self.object_id, self.username, self.password, self.email_address )
예제 #41
0
    def get(self):

        template_values = {
            'topusers' : User.get_top10()
        }

        template = jinja_environment.get_template('halloffame.html')
        self.response.out.write(template.render(template_values))
예제 #42
0
def delete(id):
    user = User.find(id)
    if user is not None:
        user.delete()
        return json_response(200, "Usuário excluído com sucesso", None)
    else:
        raise ValidationException(
            'id', 'Não existe usuário com o id %d informado' % id)
예제 #43
0
  def index( self, start = 0, count = 50, note_id = None, user_id = None ):
    """
    Provide the information necessary to display the current threads within a forum.

    @type start: integer or NoneType
    @param start: index of first forum thread to display (optional, defaults to 0)
    @type count: integer or NoneType
    @param count: how many forum threads to display (optional, defaults to quite a few)
    @type note_id: unicode or NoneType
    @param note_id: id of thread to redirect to (optional, legacy support for old URLs)
    @type user_id: unicode or NoneType
    @param user_id: id of the current user
    @rtype: unicode
    @return: rendered HTML page
    """
    if note_id:
      return dict( redirect = os.path.join( cherrypy.request.path, note_id ) )

    result = self.__users.current( user_id )
    parents = [ notebook for notebook in result[ u"notebooks" ] if notebook.trash_id and not notebook.deleted ]
    if len( parents ) > 0:
      result[ "first_notebook" ] = parents[ 0 ]
    else:
      result[ "first_notebook" ] = None

    anonymous = self.__database.select_one( User, User.sql_load_by_username( u"anonymous" ), use_cache = True )
    if anonymous is None:
      raise Access_error()

    # load a slice of the list of the threads in this forum, excluding those with a default name
    threads = self.__database.select_many(
      Notebook,
      anonymous.sql_load_notebooks(
        parents_only = False, undeleted_only = True, tag_name = u"forum", tag_value = self.__name,
        exclude_notebook_name = self.DEFAULT_THREAD_NAME, reverse = True,
        start = start, count = count,
      )
    )

    # if there are no matching threads, then this forum doesn't exist
    if len( threads ) == 0:
      raise cherrypy.NotFound

    # count the total number of threads in this forum, excluding those with a default name
    total_thread_count = self.__database.select_one(
      int,
      anonymous.sql_count_notebooks(
        parents_only = False, undeleted_only = True, tag_name = u"forum", tag_value = self.__name,
        exclude_notebook_name = self.DEFAULT_THREAD_NAME,
      )
    )

    result[ "forum_name" ] = self.__name
    result[ "threads" ] = threads
    result[ "start" ] = start
    result[ "count" ] = count
    result[ "total_thread_count" ] = total_thread_count
    return result
예제 #44
0
    def cancel_reservation(self, token, reservationid):
        """Cancel Reservation"""
        response = self.authservice.get_email_from_token(token)
        if not response['status']:
            return False
        user = User(response['email'])
        if user.balance is None:
            user.balance = Decimal(0)
        reservation = self.get_user_reservation_for_id(user, reservationid)
        if reservation is None or reservation.reservation_start is None:
            return False
        if reservation.parking_start is not None:
            return False

        spot = ParkingSpot(reservation.spot_id)
        lot = ParkingLot(spot.lot_id)
        reservation.parking_start = reservation.parking_end = datetime.now()

        user.balance -= reservation.reservation_fee
        user.save()
        user.flush()

        lot.removeReservation(reservation.spot_id)
        reservation.remove_mapping()
        return True
예제 #45
0
    def update_user_data(self, token: str, updata: dict, join: bool) -> dict:
        """Update User information"""
        user = self.authservice.get_email_from_token(token)
        if "status" not in user or not user["status"]:
            return {"status": False, "message": "Invalid Token."}
        if any(k in updata
               for k in ["password", "balance", "dataflags", "user_id"]):
            return {"status": False, "message": "Invalid Arguments."}
        wuser = User(user["email"])

        for field in [
                'first_name', 'last_name', 'street', 'number', 'plz', 'city',
                'country', 'client_settings'
        ]:
            if field in updata:
                if join and field == 'client_settings':
                    j = json.loads(wuser.client_settings)  # type: json
                    j2 = json.loads(updata[field])
                    merge(j, j2)
                    wuser.client_settings = json.dumps(j)
                else:
                    setattr(wuser, field, updata[field])

        wuser.save()
        wuser.flush()
        return {"status": True}
    def get_user(self, face_id: str) -> Optional[User]:
        if not face_id:
            return None
        user = self.__get_collection(self.COLLECTION_NAME)\
            .find_one({'faces' : {'$in' : [face_id]}})
        if not user:
            return None

        return User(user['_id'], user['name'])
예제 #47
0
def getLocation(update, context):
    currUser = User(update.effective_user.first_name,
                    update.effective_user.full_name,
                    update.effective_user.id,
                    update.effective_user.is_bot,
                    update.effective_user.last_name,
                    update.effective_user.name)
    message = None
    if update.edited_message:
        message = update.edited_message
    else:
        message = update.message
    current_pos = (message.location.latitude, message.location.longitude)
    currUser.setLocation(message.location.latitude, message.location.longitude)

    print(current_pos)
    setSharingLocationUser(currUser)
    saveLocationToExcel(currUser)
예제 #48
0
 def initialize(self, service_config, mysql_handler, redis_handler, LOG):
     self.push_queue = service_config['push_message_queue']
     self.mysql_handler = mysql_handler
     self.redis_handler = redis_handler
     self.LOG = LOG
     self.user = User(mysql_handler, LOG)
     self.order = Order(mysql_handler, LOG)
     self.rsp_handler = CommResponse()
     return
예제 #49
0
    def setUp(self):
        self.object_id = u"17"
        self.username = u"bob"
        self.password = u"foobar"
        self.email_address = u"*****@*****.**"
        self.delta = timedelta(seconds=1)

        self.user = User.create(self.object_id, self.username, self.password,
                                self.email_address)
예제 #50
0
파일: Topic.py 프로젝트: Timuer/BBS
 def new_and_save(cls, form=None, **kwargs):
     m = cls.new(form, **kwargs)
     user_id = form.get("user_id")
     user = User.find_by_id(int(user_id))
     m.username = user.username
     board_id = form.get("board_id")
     m.board = Board.find_by_id(board_id).title
     m.save()
     return m
예제 #51
0
    def find(self, email):
        query = "SELECT * FROM Users WHERE email='{}'".format(email)
        row = self.execute_query(query)

        if row:
            u = User(row[0][0], row[0][1], row[0][2])
            return u

        return None
예제 #52
0
def getUsers(ref):
    objUsers = ref.reference('user').get()
    listUsers = []
    for userID in objUsers:
        phone = objUsers[userID]['phone']
        isExposed = objUsers[userID]['expose']
        key = objUsers[userID]['key']
        listUsers.append(User(userID, phone, key, isExposed))
    return listUsers
예제 #53
0
def user_profile(request):
	us = User.find_by(username=current_user(request).username)
	body = template(
		'profile.html',
		id=str(getattr(us, 'id')),
		username=current_user(request).username,
		note=current_user(request).username
	)
	return http_response(body)
예제 #54
0
 def validate_user(self, email, password):
     """check for valid user credentials"""
     try:
         User(email, password, readonly=True)
     except NotFoundException:
         return {
             "status": False,
             "message": "Invalid mail address or password."
         }
     return {"status": True}
예제 #55
0
파일: auth_routes.py 프로젝트: Timuer/BBS
def login_post():
    form = request.form
    u = User.validate_login(form)
    if u:
        session["user_id"] = u.id
        session.permanent = True
        return redirect(url_for("topic.index"))
    else:
        token = generate_token()
        return render_template("login.html", token=token, messages="用户名或密码错误")
예제 #56
0
 def findUserByEmail(self, email):
     # if not isinstance(email, str):
     #     raise Exception("Email is not a string")
     # bivinno exception khaite paare: db down, busy, user paay nai, fail korse db te.
     # user related kaaj gula show korbo, baki sob log korbo.
     try:
         if User.get(User.email == email):
             return "User found"
     except peewee.DoesNotExist:
         return "User Not found"
예제 #57
0
class UserController():
    def __init__(self):
        self.user_model = User()

    def login(self, email, password):
        self.user_model.email = email
        result = self.user_model.get_user_bye_mail()
        if result is not None:
            res = self.user_model.verify_password(password, result.password)
            if res:
                return result
            else:
                return {}
        return {}

    def verify_auth_token(self, access_token):
        status = 401
        try:
            jwt.decode(access_token, config.SECRET, algorithms='HS256')
            message = 'Valid Token'
            status = 200
        except jwt.ExpiredSignatureError:
            message = 'Token has expired, make login again'
        except:
            message = 'Invalid Token'
        return {'message': message, 'status': status}

    def generate_auth_token(self, data, exp=30, time_exp=False):
        if time_exp == True:
            data_time = data['exp']
        else:
            date_time = datetime.utcnow() + timedelta(minutes=exp)

        dict_jwt = {
            'id': data['id'],
            'username': data['username'],
            'exp': date_time
        }
        access_token = jwt.encode(dict_jwt, config.SECRET, algorithm='HS256')
        return access_token

    def recovery(email):
        return ""
예제 #58
0
def login_do():
    username = request.form.get('username')
    password = request.form.get('password')
    users = User.select().where(User.username == username, User.password==password)
    if len(users) != 0:
        if users[0].password == password:
            # login success
            session['userid'] = users[0].get_id()
            return redirect(url_for('search'))
    return render_template("login.html")
예제 #59
0
 def fetch_reservation_data_for_id(self, token, res_id):
     """Get Details of specific Reservation"""
     response = self.authservice.get_email_from_token(token)
     if not response['status']:
         return False
     user = User(response['email'], readonly=True)
     r = next((x for x in user.reservations if x.res_id == res_id), None)
     if r is None:
         return False
     return r.get_data_dict()