Esempio n. 1
0
    def get_user(self):
        """ Returns the user using the Graph API. """

        if not self.accessToken():
            return None

        if not self.graph:
            self.graph = self.GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object_c("me")
        except self.GraphAPIError:
            current.session.token = None
            self.graph = None

        if user:
            # Check if a user with this email has already registered
            #session = current.session
            #session.facebooklogin = True
            auth = current.auth
            table = auth.settings.table_user
            query = (table.email == user["email"])
            existent = current.db(query).select(table.id,
                                                table.password,
                                                limitby=(0, 1)).first()
            if existent:
                #session["%s_setpassword" % existent.id] = existent.password
                _user = dict(first_name = user.get("first_name", ""),
                             last_name = user.get("last_name", ""),
                             facebookid = user["id"],
                             facebook = user.get("username", user["id"]),
                             email = user["email"],
                             password = existent.password
                            )
                return _user
            else:
                # b = user["birthday"]
                # birthday = "%s-%s-%s" % (b[-4:], b[0:2], b[-7:-5])
                # if 'location' in user:
                #     session.flocation = user['location']
                #session["is_new_from"] = "facebook"
                auth.s3_send_welcome_email(user)
                # auth.initial_user_permission(user)  # Called on profile page
                _user = dict(first_name = user.get("first_name", ""),
                             last_name = user.get("last_name", ""),
                             facebookid = user["id"],
                             facebook = user.get("username", user["id"]),
                             nickname = IS_SLUG()(user.get("username", "%(first_name)s-%(last_name)s" % user) + "-" + user['id'][:5])[0],
                             email = user["email"],
                             # birthdate = birthday,
                             about = user.get("bio", ""),
                             website = user.get("website", ""),
                             # gender = user.get("gender", "Not specified").title(),
                             photo_source = 3,
                             tagline = user.get("link", ""),
                             registration_type = 2,
                            )
                return _user
Esempio n. 2
0
    def get_user(self):
        """ Returns the user using the Graph API. """

        token = self.accessToken()

        if not token:
            return None

        if not self.graph:
            self.graph = self.GraphAPI(token)

        user = None
        try:
            user = self.graph.get_object_c("me")
        except self.GraphAPIError:
            current.session.token = None
            self.graph = None

        user_dict = None

        if user:
            # Check if a user with this email has already registered
            #session = current.session
            #session.facebooklogin = True

            table = current.auth.settings.table_user

            query = (table.email == user["email"])
            existing = current.db(query).select(table.id,
                                                table.password,
                                                limitby=(0, 1)).first()
            if existing:
                #session["%s_setpassword" % existing.id] = existing.password

                user_dict = {
                    "first_name": user.get("first_name", ""),
                    "last_name": user.get("last_name", ""),
                    "facebookid": user["id"],
                    "facebook": user.get("username", user["id"]),
                    "email": user["email"],
                    "password": existing.password,
                }

            else:
                # b = user["birthday"]
                # birthday = "%s-%s-%s" % (b[-4:], b[0:2], b[-7:-5])
                # if 'location' in user:
                #     session.flocation = user['location']
                #session["is_new_from"] = "facebook"

                # Done in s3_approve_user()
                #auth.s3_send_welcome_email(user)

                user_dict = {
                    "first_name":
                    user.get("first_name", ""),
                    "last_name":
                    user.get("last_name", ""),
                    "facebookid":
                    user["id"],
                    "facebook":
                    user.get("username", user["id"]),
                    "nickname":
                    IS_SLUG()(user.get("username",
                                       "%(first_name)s-%(last_name)s" % user) +
                              "-" + user['id'][:5])[0],
                    "email":
                    user["email"],
                    #"birthdate": birthday,
                    "about":
                    user.get("bio", ""),
                    "website":
                    user.get("website", ""),
                    #"gender": user.get("gender", "Not specified").title(),
                    "photo_source":
                    3,
                    "tagline":
                    user.get("link", ""),
                    "registration_type":
                    2,
                }
        return user_dict
Esempio n. 3
0
 def process(self,request,response,policies=None):
     """ the main method, processes a request, filters by policies and produces a JSON response """
     self.request = request
     self.response = response
     self.policies = policies
     db = self.db
     tablename = request.args(0)
     r = OrderedDict()
     r['version'] = self.VERSION
     tablenames = policies.keys() if policies else db.tables
     # if there is no tables
     if not tablename:
         r['href'] = URL(scheme=True),
         # https://github.com/collection-json/extensions/blob/master/model.md
         r['links'] = [{'rel' : t, 'href' : URL(args=t,scheme=True), 'model':t} 
                       for t in tablenames]
         response.headers['Content-Type'] = 'application/vnd.collection+json'
         return response.json({'collection':r})
     # or if the tablenames is invalid
     if not tablename in tablenames:
         return self.error(400,'BAD REQUEST','Invalid table name')
     # of if the method is invalid
     if not request.env.request_method in policies[tablename]:
         return self.error(400,'BAD REQUEST','Method not recognized')
     # get the policies
     self.table_policy = policies[tablename][request.env.request_method]
     # process GET
     if request.env.request_method=='GET':
         table = db[tablename]
         r['href'] = URL(args=tablename)        
         r['items'] = items = []
         try:
             (query, limitby, orderby) = self.request2query(table,request.get_vars)
             fields = [table[fn] for fn in (self.table_policy.get('fields', table.fields))]
             fields = filter(lambda field: field.readable, fields)
             rows = db(query).select(*fields,**dict(limitby=limitby, orderby=orderby))
         except:
             db.rollback()
             return self.error(400,'BAD REQUEST','Invalid Query')
         r['items_found'] = db(query).count()
         delta = limitby[1]-limitby[0]-1
         r['links'] = self.row2links(table,None) if self.compact else []
         text = r['items_found']<2
         for row in rows[:delta]:
             id = row.id
             for name in ('slug','fullname','title','name'):
                 if name in row:
                     href = URL(args=(tablename,id,IS_SLUG.urlify(row[name] or '')),
                                scheme=True)
                     break
             else:
                 href = URL(args=(tablename,id),scheme=True)
             if self.compact:
                 items.append(self.row2data(table,row,text))
             else:
                 items.append({
                         'href':href,
                         'data':self.row2data(table,row,text),
                         'links':self.row2links(table,row)
                         });
         if self.extensions and len(rows)>delta:
             vars = dict(request.get_vars)
             vars['_offset'] = limitby[1]-1
             vars['_limit'] = limitby[1]-1+delta
             r['next'] = {'rel':'next',
                          'href':URL(args=request.args,vars=vars,scheme=True)}
         if self.extensions and limitby[0]>0:
             vars = dict(request.get_vars)
             vars['_offset'] = max(0,limitby[0]-delta)
             vars['_limit'] = limitby[0]
             r['previous'] = {'rel':'previous',
                              'href':URL(args=request.args,vars=vars,scheme=True)}
         data = []
         if not self.compact:
             r['queries'] = self.table2queries(table, r['href'])
         r['template'] = self.table2template(table)
         response.headers['Content-Type'] = 'application/vnd.collection+json'
         return response.json({'collection':r})
     # process DELETE
     elif request.env.request_method=='DELETE':
         table = db[tablename] 
         if not request.get_vars:
             return self.error(400, "BAD REQUEST", "Nothing to delete")
         else:
             try:
                 (query, limitby, orderby) = self.request2query(table, request.vars)
                 n = db(query).delete() # MAY FAIL
                 response.status = 204
                 return ''
             except:
                 db.rollback()
                 return self.error(400,'BAD REQUEST','Invalid Query')
         return response.json(r)
     # process POST and PUT (on equal footing!)
     elif request.env.request_method in ('POST','PUT'): # we treat them the same!
         table = db[tablename]
         if 'json' in request.env.content_type:
             data = request.post_vars.data
         if request.get_vars or len(request.args)>1: # update
             # ADD validate fields and return error
             try:
                 (query, limitby, orderby) = self.request2query(table, request.get_vars)
                 fields = filter(lambda (fn,value):table[fn].writable,data.items())
                 res = db(query).validate_and_update(**dict(fields)) # MAY FAIL
                 if res.errors:
                     return self.error(400,'BAD REQUEST','Validation Error',res.errors)
                 else:
                     response.status = 200
                     return ''
             except:
                 db.rollback()
                 return self.error(400,'BAD REQUEST','Invalid Query')
         else: # create
             # ADD validate fields and return error
             try:
                 fields = filter(lambda (fn,value):table[fn].writable,data.items())
                 res = table.validate_and_insert(**dict(fields)) # MAY FAIL
                 if res.errors:
                     return self.error(400,'BAD REQUEST','Validation Error',res.errors)
                 else:
                     response.status = 201
                     response.headers['location'] = \
                         URL(args=(tablename,res.id),scheme=True)
                     return ''
             except SyntaxError,e: #Exception,e:
                 db.rollback()
                 return self.error(400,'BAD REQUEST','Invalid Query:'+e)
Esempio n. 4
0
 def process(self, request, response, policies=None):
     """ the main method, processes a request, filters by policies and produces a JSON response """
     self.request = request
     self.response = response
     self.policies = policies
     db = self.db
     tablename = request.args(0)
     r = OrderedDict()
     r['version'] = self.VERSION
     tablenames = policies.keys() if policies else db.tables
     # if there is no tables
     if not tablename:
         r['href'] = URL(scheme=True),
         # https://github.com/collection-json/extensions/blob/master/model.md
         r['links'] = [{
             'rel': t,
             'href': URL(args=t, scheme=True),
             'model': t
         } for t in tablenames]
         response.headers[
             'Content-Type'] = 'application/vnd.collection+json'
         return response.json({'collection': r})
     # or if the tablenames is invalid
     if not tablename in tablenames:
         return self.error(400, 'BAD REQUEST', 'Invalid table name')
     # of if the method is invalid
     if not request.env.request_method in policies[tablename]:
         return self.error(400, 'BAD REQUEST', 'Method not recognized')
     # get the policies
     self.table_policy = policies[tablename][request.env.request_method]
     # process GET
     if request.env.request_method == 'GET':
         table = db[tablename]
         r['href'] = URL(args=tablename)
         r['items'] = items = []
         try:
             (query, limitby,
              orderby) = self.request2query(table, request.get_vars)
             fields = [
                 table[fn]
                 for fn in (self.table_policy.get('fields', table.fields))
             ]
             fields = filter(lambda field: field.readable, fields)
             rows = db(query).select(
                 *fields, **dict(limitby=limitby, orderby=orderby))
         except:
             db.rollback()
             return self.error(400, 'BAD REQUEST', 'Invalid Query')
         r['items_found'] = db(query).count()
         delta = limitby[1] - limitby[0] - 1
         r['links'] = self.row2links(table, None) if self.compact else []
         text = r['items_found'] < 2
         for row in rows[:delta]:
             id = row.id
             for name in ('slug', 'fullname', 'title', 'name'):
                 if name in row:
                     href = URL(args=(tablename, id,
                                      IS_SLUG.urlify(row[name] or '')),
                                scheme=True)
                     break
             else:
                 href = URL(args=(tablename, id), scheme=True)
             if self.compact:
                 items.append(self.row2data(table, row, text))
             else:
                 items.append({
                     'href': href,
                     'data': self.row2data(table, row, text),
                     'links': self.row2links(table, row)
                 })
         if self.extensions and len(rows) > delta:
             vars = dict(request.get_vars)
             vars['_offset'] = limitby[1] - 1
             vars['_limit'] = limitby[1] - 1 + delta
             r['next'] = {
                 'rel': 'next',
                 'href': URL(args=request.args, vars=vars, scheme=True)
             }
         if self.extensions and limitby[0] > 0:
             vars = dict(request.get_vars)
             vars['_offset'] = max(0, limitby[0] - delta)
             vars['_limit'] = limitby[0]
             r['previous'] = {
                 'rel': 'previous',
                 'href': URL(args=request.args, vars=vars, scheme=True)
             }
         data = []
         if not self.compact:
             r['queries'] = self.table2queries(table, r['href'])
         r['template'] = self.table2template(table)
         response.headers[
             'Content-Type'] = 'application/vnd.collection+json'
         return response.json({'collection': r})
     # process DELETE
     elif request.env.request_method == 'DELETE':
         table = db[tablename]
         if not request.get_vars:
             return self.error(400, "BAD REQUEST", "Nothing to delete")
         else:
             try:
                 (query, limitby,
                  orderby) = self.request2query(table, request.vars)
                 n = db(query).delete()  # MAY FAIL
                 response.status = 204
                 return ''
             except:
                 db.rollback()
                 return self.error(400, 'BAD REQUEST', 'Invalid Query')
         return response.json(r)
     # process POST and PUT (on equal footing!)
     elif request.env.request_method in ('POST',
                                         'PUT'):  # we treat them the same!
         table = db[tablename]
         if 'json' in request.env.content_type:
             data = request.post_vars.data
         else:
             data = request.post_vars
         if request.get_vars or len(request.args) > 1:  # update
             # ADD validate fields and return error
             try:
                 (query, limitby,
                  orderby) = self.request2query(table, request.get_vars)
                 fields = filter(
                     lambda fn_value: table[fn_value[0]].writable,
                     data.items())
                 res = db(query).validate_and_update(**dict(
                     fields))  # MAY FAIL
                 if res.errors:
                     return self.error(400, 'BAD REQUEST',
                                       'Validation Error', res.errors)
                 else:
                     response.status = 200
                     return ''
             except:
                 db.rollback()
                 return self.error(400, 'BAD REQUEST', 'Invalid Query')
         else:  # create
             # ADD validate fields and return error
             try:
                 fields = filter(
                     lambda fn_value1: table[fn_value1[0]].writable,
                     data.items())
                 res = table.validate_and_insert(**dict(fields))  # MAY FAIL
                 if res.errors:
                     return self.error(400, 'BAD REQUEST',
                                       'Validation Error', res.errors)
                 else:
                     response.status = 201
                     response.headers['location'] = \
                         URL(args=(tablename,res.id),scheme=True)
                     return ''
             except SyntaxError as e:  #Exception,e:
                 db.rollback()
                 return self.error(400, 'BAD REQUEST', 'Invalid Query:' + e)