Пример #1
0
 def validate(self):
     if not Form.validate(self):
         return False
     if self.username.data == self.original_username:
         return True
     if self.username.data != Users.make_valid_username(self.username.data):
         self.username.errors.append(
             gettext("This username has invalid characters. Please use letters, numbers, dots and underscores only.")
         )
         return False
     user = Users.query.filter_by(username=self.username.data).first()
     if self.password.data != Users.make_valid_password(self.password.data):
         self.username.errors.append(
             gettext("This password has invalid characters. Please use letters, numbers, dots and underscores only.")
         )
         return False
     password = Users.query.filter_by(password=self.password.data).first()
     if self.email.data != Users.make_valid_email(self.email.data):
         self.username.errors.append(
             gettext("This email has invalid characters. Please use letters, numbers, dots and underscores only.")
         )
         return False
     email = Users.query.filter_by(email=self.email.data).first()
     if user != None:
         self.username.errors.append(gettext("This username is already in use. Please choose another one."))
         return False
     return True
Пример #2
0
def insertUserProfile(payload):
    try:
        user = Users(
            name=payload['name'], 
            lastname=payload['surname'],
            username=payload['username'], 
            gender=payload['gender'],
            pwd=-1, 
            email=payload['mail'],
            mobile=payload['phone'], 
            country=payload['country'], 
            city=payload['city'], 
            address=payload['address'], 
            postal_code=payload['postcode'], 
            is_active=True,
            experience=ItExperience.objects.get(level__iexact=payload['skills']), 
            last_login=datetime.today(),
            registration=datetime.today()
        )
        user.save()
        return user
    except Exception as ex:
        logger.exception(str(ex))
        if settings.DEBUG:
            print_exc()
        return -1
Пример #3
0
def registrate(email, nickname, passwd, passwd_chk):
  email_splitted = email.split('@')
  if len(email_splitted) != 2:
    flash('Email address isn\'t correct. Try again')
    return redirect(url_for('signup'))
  if nickname == '':
    nickname = email_splitted[0]

  if Users.query.filter_by(nickname = nickname).first() is not None:
    flash('The user with such nickname already exist. Try another nickname')
    return redirect(url_for('signup'))

  if passwd != passwd_chk:
    flash('The passwords don\'t match. Try again')
    return redirect(url_for('signup'))

  user = Users.query.filter_by(email = email).first()
  if user is not None:
    flash('The user with such email already exist. Try another email')
    return redirect(url_for('signup'))
  else:
    user = Users(email = email, nickname = nickname, passwd = passwd)
    user.set_password(passwd)
    db.session.add(user)
    firstTree = Tree(user, "firstTree")

    # for tests
    rootb = firstTree.rootb
    b1 = Branch(text="branch1_" + str(firstTree.name), parent=rootb)
    b11 = Branch(text="branch11_" + str(firstTree.name), parent=b1)
    b12 = Branch(text="branch12_" + str(firstTree.name), parent=b1)
    #

    db.session.commit()
    return redirect(url_for('success_signup'))
Пример #4
0
def registrate(username, passwd, email):
    user = Users.query.filter_by(nickname = username).first()
    if user is not None:
        flash('Such user already exist. Try another username')
        return redirect(url_for('registration'))
    else:
        user = Users(nickname = username, passwd = passwd, email = email)
        user.set_password(passwd)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('success_registration'))
Пример #5
0
    def insert_user(self, token, name, last_name, email):
        if token:
            response = Users(
                token=token,
                name=name,
                last_name=last_name,
                email=email,
                created_at=datetime.datetime.now())
            response.save()

            return True

        return False
Пример #6
0
def view_bucket_list():
    '''A method that returns the route of viewbucketlist in the html.  '''
    prompt = "You currently have no bucketlists on the bucket list,"
    prompt += " press the create new bucket list button to create a new bucket!"
    if request.method == "POST":
        return redirect(url_for('create_bucket_list'))
    bucket_items = BucketList().view_bucket()
    name_of_user = Users().users[Users.get_id()].user_name.upper()
    if name_of_user.endswith('s'):
        name_of_user += "'"
    else:
        name_of_user += "'s"
    return render_template("ViewBucketList.html", bucket_items=bucket_items, prompt=prompt, name_of_user=name_of_user)
Пример #7
0
    def post(self):
        raw_dict = request.get_json(force=True)
        try:
            user = Users(raw_dict['email'], raw_dict['password'], raw_dict['name'], raw_dict['active'])
            user.add(user)
            # Should not return password hash
            query = Users.query.get(user.id)
            results = schema.dump(query)
            return results, 201

        except SQLAlchemyError as e:
            db.session.rollback()
            resp = jsonify({"error": str(e)})
            resp.status_code = 403
            return resp
Пример #8
0
	def POST(self):
		loginform = LoginForm()
		if not loginform.validates():
			return self.__makepage(loginform)
		user = Users.get_by_username(loginform.username.value)
		session.signin(user.id)
		return web.seeother('/')
Пример #9
0
 def validate(self):
     if request.form["user_name"] is None or request.form["user_name"].strip()=="":
         return False
     inserted_username = request.form["user_name"]
     user = Users.query.filter_by(user_name = inserted_username).first()
     if user != None:
         suggested_username = Users.create_unique_username(inserted_username)
         flash('This username already exists. Consider register with %s' % suggested_username)
         return False
     return True
Пример #10
0
def do_reg():
	from app.models import Users
	_uname = request.form['username'].strip()
	_pwd = request.form['password'].strip()
#	检验数据
	if len(_uname)>20 or len(_uname)<5:
		return '用户名要求长度5-20'
	elif len(_pwd)>20 or len(_pwd)<8:
		return '密码要求长度8-20'
	else:
		exists_users = Users.objects.filter(username = request.form['username'])
		if exists_users.count()>0:
			return '帐号已存在'
#	执行注册	
	new_user = Users(
		username = _uname,
		password = _pwd
	)
	new_user.save()	
	return '注册成功'
Пример #11
0
def userslist():
  user = g.user
  if request.method == "GET":
    req_str = request.args.get('q', default='', type=str)
    req_str = req_str.replace(' ', '')

    res = []
    for curuser in Users.getUsersList():
      if curuser.id != user.id and ( req_str == '' or curuser.nickname.find(req_str) == 0 ):
        res.append({ 'id' : curuser.id, 'name' : curuser.nickname })

    return json.dumps(res)
Пример #12
0
    def post(self):
        raw_dict = request.get_json(force=True)
        try:
            schema.validate(raw_dict)
            request_dict = raw_dict['data']['attributes']
            print(raw_dict)
            user = Users(request_dict['name'], request_dict['email'])
            user.add(user)
            # Shouldn't return password hash
            query = Users.query.get(user.id)
            results = schema.dump(query).data
            return results, 201

        except ValidationError as err:
            resp = jsonify({"error": err.messages})
            resp.status_code = 403
            return resp

        except SQLAlchemyError as e:
            db.session.rollback()
            resp = jsonify({"error": str(e)})
            resp.status_code = 403
            return resp
Пример #13
0
    def getNewUser(self):

        user = Users()
        user.user_login = self.__user_login
        user.user_name = self.__user_name
        user.user_pass = self.__user_pass
        user.user_phone = self.__user_phone
        user.school_id = self.__school_id
        user.user_rule = self.__user_rule

        db.session.add(user)
        db.session.commit()

        return user
Пример #14
0
def facebook(request):
    host = request.get_host()
    """

    :param request:
    :return:
    """
    params = {
        'client_id': settings.FACEBOOK_APP_ID,
        'redirect_uri': 'http://'+host+'/facebook',
        'client_secret': settings.FACEBOOK_SECRET_KEY,
        'code': request.GET['code']
    }

    http = httplib2.Http(timeout=15)
    response, content = http.request('https://graph.facebook.com/oauth/access_token?%s' % urllib.urlencode(params))
    print response
    print content
    # Find access token and expire (this is really gross)
    params = content.split('&')
    ACCESS_TOKEN = params[0].split('=')[1]
    EXPIRE = params[1].split('=')[1]

    # Get basic information about the person
    response, content = http.request('https://graph.facebook.com/me?access_token=%s' % ACCESS_TOKEN)
    data = json.loads(content)
    # Try to find existing profile, create a new user if one doesn't exist
    try:
        user = Users.objects.get(facebook_uid=data['id'])
        #request.session['data']=data
        # print request.session.get('data','not working')
    except Users.DoesNotExist:
        user = Users()
        user.facebook_uid = data['id']
        user.user = data['name']
        user.facebook_access_token = ACCESS_TOKEN
        user.facebook_access_token_expires = EXPIRE
        user.save()

        #login(request, user)

    request.session['user'] = user
    request.session['block_sources'] = "initial"
    print request.session.get('user', 'Not working')

    # # Authenticate and log user in
    #     user = authenticate(username=profile.user.username, password=profile.facebook_uid)

    return HttpResponseRedirect('/home')
    # return render(request, "settings.html", data)
Пример #15
0
def showBranch_byPath(user_name=None, tree_name=None, branch_id=None):
  user = None
  trees = None
  if g.user is not None and g.user.is_authenticated():
    user = g.user
    trees = user.allTrees()

  tree_owner = Users.getUser(nickname = user_name)
  if tree_owner != None:
    tree = tree_owner.getTree(name=tree_name)
    if tree != None:
      branch = tree.getB(branch_id)
      if branch != None:
        return render_template("tree.html",
                                title='Tree',
                                curtree=tree,
                                trees=trees,
                                user=user,
                                latestUsedB=branch.id)
  flash("Can't find the branch by current path")
  return render_template("base.html")
Пример #16
0
def mngtrees():
  user = Users.getUser(email=g.user.email)

  if request.method == "GET":
    cmd = request.args.get('cmd', default='', type=str)

    if cmd == "create_tree":
      try:
        treename = request.args.get('name', default='NewTree', type=str)
        if user.getTree(name=treename) != None:
          raise BaseException
        createdTree = Tree(user, treename)
        return jsonify({ 'id' : createdTree.id, 'name' : createdTree.name })
      except BaseException:
        return jsonify({ 'error' : "Error: The tree with such name exists. Try another name.", })
    elif cmd == "remove_tree":
      try:
        tree_id = request.args.get('tree_id', default=None, type=int)
        tree = user.getTree(id=tree_id)
        tree.remove()
        return "True"
      except BaseException:
        return "False"
    elif cmd == "rename_tree":
      try:
        tree_id = request.args.get('tree_id', default=None, type=int)
        newname = request.args.get('newname', default='Tree', type=str)
        if user.getTree(name=newname) != None:
          raise BaseException
        tree = user.getTree(id=tree_id)
        tree.rename(newname)
        return ""
      except BaseException:
        return "Error: The tree with such name exists. Try another name."

  db.session.commit()
  return ""
Пример #17
0
 def test_follow(self):
     # create a friend
     u1 = Users(username='******', email='*****@*****.**', password= '******')
     u2 = Users(username='******', email='*****@*****.**', password = '******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     assert u1.unfollow(u2) == None
     u = u1.follow(u2)
     db.session.add(u)
     db.session.commit()
     assert u1.follow(u2) == None
     assert u1.is_following(u2)
     assert u1.followed.count() == 1
     assert u1.followed.first().username == 'susan'
     assert u2.followers.count() == 1
     assert u2.followers.first().username == 'john'
     u = u1.unfollow(u2)
     assert u != None
     db.session.add(u)
     db.session.commit()
     assert u1.is_following(u2) == False
     assert u1.followed.count() == 0
     assert u2.followers.count() == 0
Пример #18
0
 def test_avatar(self):
     # create a user
     u = Users(username='******', email='*****@*****.**', password = '******')
     avatar = u.avatar(128)
     expected = 'http://www.gravatar.com/avatar/d4c74594d841139328695756648b6bd6'
     assert avatar[0:len(expected)] == expected
Пример #19
0
class LoginTestCase(unittest.TestCase):
    '''A class used to run tests on the Users class in models.py.  '''


    def setUp(self):
        '''Creating an object from the models.py file for the class Users.  '''
        self.user = Users()

    def test_login_entry_happy_path(self):
        '''A method to test that the login in works with the right inputs.  '''
        self.user.users.clear()
        self.user.create_user("user1", "*****@*****.**", "password1", "password1")
        boolean_for_login_user = self.user.login_user("*****@*****.**", "password1")
        self.assertEqual(boolean_for_login_user, True)

    def test_login_entry_sad_path_1(self):
        '''A method to test that login does not work with wrong input of user email.  '''
        self.user.users.clear()
        self.user.create_user("user1", "*****@*****.**", "password1", "password1")
        boolean_for_login_user = self.user.login_user("*****@*****.**", "password1")
        self.assertEqual(boolean_for_login_user, None)

    def test_login_entry_sad_path_2(self):
        '''A method to test that login does not work with wrong input of password.  '''
        self.user.users.clear()
        self.user.create_user("user1", "*****@*****.**", "password1", "password1")
        boolean_for_login_user = self.user.login_user("*****@*****.**", "password2")
        self.assertEqual(boolean_for_login_user, None)

    def test_login_sets_right_user_id(self):
        '''A method to test that the right user id is set on login.  '''
        self.user.users.clear()
        self.user.create_user("user1", "*****@*****.**", "password1", "password1")
        self.user.create_user("user2", "*****@*****.**", "password2", "password2")
        self.user.create_user("user3", "*****@*****.**", "password3", "password3")
        self.user.login_user("*****@*****.**", "password3")
        self.assertEqual(models.USER_ID, 2)
        self.user.login_user("*****@*****.**", "password2")
        self.assertEqual(models.USER_ID, 1)
        self.user.login_user("*****@*****.**", "password1")
        self.assertEqual(models.USER_ID, 0)
Пример #20
0
 def setUp(self):
     '''Creating an object from the models.py file for the class Users.  '''
     self.user = Users()
Пример #21
0
import json, re

from app.helpers import render, utils, session

from app.models import Users

val_username	= form.regexp(r'^\w[\w\d_]{2,19}$', 'must be betweem 3 and 20 characters. username should containt only latin alphabet, digits and underscores')
val_password	= form.regexp(r'^.{3,}$', 'must have more than 3 characters')
val_email		= form.regexp(r'^[email protected]+$', 'must be a valid email address')

LoginForm = form.Form(
	form.Textbox('username', val_username, description='Username'),
	form.Password('password',val_password, description='Password'),	
	form.Button('submit', type='submit', html='Sign in'),
	validators = [
		form.Validator("Username or Password is incorrect", lambda i: Users.check(i.username, i.password)),
	]
)

class Signin:
	def __makepage(self, loginform = None):
		if loginform is None: loginform = LoginForm()
		return render.layout(view.signin(loginform), title="Sign in")

	def GET(self):
		return self.__makepage()

	def POST(self):
		loginform = LoginForm()
		if not loginform.validates():
			return self.__makepage(loginform)
Пример #22
0
 def test_follow_posts(self):
     # make four users
     u1 = Users(username='******', email='*****@*****.**', password = '******')
     u2 = Users(username='******', email='*****@*****.**', password = '******')
     u3 = Users(username='******', email='*****@*****.**', password = '******')
     u4 = Users(username='******', email='*****@*****.**', password = '******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.add(u3)
     db.session.add(u4)
     # make four posts
     utcnow = datetime.utcnow()
     p1 = Post(body="post from john", author=u1,
               timestamp=utcnow + timedelta(seconds=1))
     p2 = Post(body="post from susan", author=u2,
               timestamp=utcnow + timedelta(seconds=2))
     p3 = Post(body="post from mary", author=u3,
               timestamp=utcnow + timedelta(seconds=3))
     p4 = Post(body="post from david", author=u4,
               timestamp=utcnow + timedelta(seconds=4))
     db.session.add(p1)
     db.session.add(p2)
     db.session.add(p3)
     db.session.add(p4)
     db.session.commit()
     # setup the followers
     u1.follow(u1)  # john follows himself
     u1.follow(u2)  # john follows susan
     u1.follow(u4)  # john follows david
     u2.follow(u2)  # susan follows herself
     u2.follow(u3)  # susan follows mary
     u3.follow(u3)  # mary follows herself
     u3.follow(u4)  # mary follows david
     u4.follow(u4)  # david follows himself
     db.session.add(u1)
     db.session.add(u2)
     db.session.add(u3)
     db.session.add(u4)
     db.session.commit()
     # check the followed posts of each user
     f1 = u1.followed_posts().all()
     f2 = u2.followed_posts().all()
     f3 = u3.followed_posts().all()
     f4 = u4.followed_posts().all()
     assert len(f1) == 3
     assert len(f2) == 2
     assert len(f3) == 2
     assert len(f4) == 1
     assert f1 == [p4, p2, p1]
     assert f2 == [p3, p2]
     assert f3 == [p4, p3]
     assert f4 == [p4]
Пример #23
0
def mngtree():
  #for_test()

  # get data from request
  ## via GET method
  if request.method == "GET":
    # curtree_id is require only for cases when jstree return '#' as a sign of root branch_id. To get rid of it we have to rewrite a big part of jstree
    try:
      curtree_id = request.args.get('tree_id', default='', type=str)
    except AttributeError as e:
      msg='Can\'t find any trees. Try to create one.'
      print('\n' + str(msg) + '\n')
      return ""

    import app.general
    nestedocs = app.general.str2bool(request.args.get('nestedocs', default='False', type=str))
    cmd = request.args.get('cmd', default='', type=str)
    id = request.args.get('id', default='', type=str)

    # after integration with flask symbole '%' has started to add to id. So we need to remove it
    if id[:1] == "%":
      id = int(id[1:])
    if id == '#' or id == None or id == '':
      curtree = Tree.getTree(id = curtree_id)
      id = curtree.rootb_id

    data = request.args.get('data', default='', type=str)

  ## via POST method
  else:
    form = SaveDataForm(request.form)
    if request.method == "POST" and form.validate():
      nestedocs = form.nestedocs.data
      cmd = form.cmd.data
      id = form.id.data
      data = form.data.data
  ##

  branch = Branch.get(id=id)
  curtree = Tree.getTree(id=branch.tree_id)
  tree_owner = curtree.owner

  """
  cmd = "load_subbs"
  id = 4
  id = '#'
  """

  # set permission for actions
  if g.user is not None and g.user.is_authenticated():
    curuser = g.user
  else:
    curuser = '******'

  owner = True
  if tree_owner.id != curuser.id:
    owner = False
    if not ( branch.read and cmd == "load_subbs" ):
      cmd = ''
  #

  if cmd != "" :
    if cmd == "fold":
      branch.folded = True
    elif cmd == "unfold":
      branch.folded = False
    elif cmd == "rename_node":
      branch.text = data
    elif cmd == "move_node":
      new_parent_id = request.args.get('new_parent', default=curtree.rootb_id, type=int)
      position = request.args.get('position', default=-1, type=int)
      branch.move(new_parent_id, position)
    elif cmd == "load_data":
      return branch.text
    elif cmd == "delete_node":
      branch.remove()
    elif cmd == "create_node":
      parent_id = request.args.get('parent_id', default=curtree.rootb_id, type=int)
      parentB = curtree.getB(parent_id)
      newB = Branch(main = (not nestedocs), parent_id = parent_id)
      position = request.args.get('position', default=-1, type=int)
      newB.move(pos=position)
      return str( newB.id )
    elif cmd == "load_subbs":
      curtree.set_latestB(id)
      return json.dumps(getList_subbsOf(branch, nestedocs, withReadLabel=(not owner)))
    elif cmd == "get_privileges":
      return json.dumps(branch.get_priv_all())
    elif cmd == "set_privileges":
      for_class = request.args.get('for_class', default='bydefault', type=str)
      priv_read = app.general.str2bool(request.args.get('read', default=None, type=str))
      priv_rw = app.general.str2bool(request.args.get('rw', default=None, type=str))
      if for_class == 'bydefault':
        new_privs = branch.set_priv_bydefault(priv_read, priv_rw)
      elif for_class == 'users':
        nickname = request.args.get('nickname', default=None, type=str)
        if nickname != None:
          user = Users.getUser(nickname = nickname)
          new_privs = branch.set_priv_foruserid(user.id, priv_read, priv_rw)
      return json.dumps(new_privs)
    elif cmd == "set_priv_adduser":
      nickname = request.args.get('nickname', default=None, type=str)
      if nickname != None:
        user = Users.getUser(nickname = nickname)
        if branch.set_priv_adduser(user) == 0:
          return 0
      return -1
    else:
      if nestedocs :
        if cmd == "save_data":
          branch.text = data
        else:
          pass
  db.session.commit()
  return ""
Пример #24
0
	def POST(self):
		regform = RegForm()
		if not regform.validates():
			return self.__makepage(regform)
		Users.add(regform)
		return web.seeother('/signin')
Пример #25
0
def removeuser():
  user = g.user
  user = Users.getUser(email=user.email)
  user.remove()
  return redirect(url_for('about'))
Пример #26
0
class RegisterTestCase(unittest.TestCase):
    '''A class to test the registering function of the users for the bucket list.  '''


    def setUp(self):
        '''Creating an object of the Users class.  '''
        self.user = Users()

    def test_create_user_happy_path(self):
        '''A method to test that a user was created successfully with all inputs
        inserted correctly according to standards required.
        '''
        self.user.users.clear()
        self.user.create_user("user4", "*****@*****.**", "password2", "password2")
        self.assertEqual(self.user.users[0].user_name, "user4")
        self.assertEqual(self.user.users[0].user_email, "*****@*****.**")
        self.assertEqual(self.user.users[0].user_password, "password2")

    def test_create_user_sad_path(self):
        '''A method to test that a user was not created with non-matching passwords.  '''
        self.user.users.clear()
        self.user.create_user("user2", "*****@*****.**", "password1", "password2")
        self.assertEqual(len(self.user.users), 0)

    def test_create_user_sad_path_2(self):
        '''A method to test that a user was not created with an empty user-name.  '''
        self.user.users.clear()
        self.user.create_user("", "*****@*****.**", "password1", "password2")
        self.assertEqual(len(self.user.users), 0)

    def test_create_user_sad_path_3(self):
        '''A method to test that a user was not created with an empty password.  '''
        self.user.users.clear()
        self.user.create_user("user2", "*****@*****.**", "", "")
        self.assertEqual(len(self.user.users), 0)

    def test_create_user_sad_path_4(self):
        '''A method to test that a user was not created with an empty email.  '''
        self.user.users.clear()
        self.user.create_user("user2", "", "ppp", "ppp")
        self.assertEqual(len(self.user.users), 0)

    def test_create_user_sad_path_5(self):
        '''A method to test that a second user was not created with a similar user-name
        as the first user.
        '''
        self.user.users.clear()
        self.user.create_user("user4", "*****@*****.**", "password2", "password2")
        self.user.create_user("user4", "*****@*****.**", "password3", "password3")
        self.assertEqual(len(self.user.users), 1)

    def test_create_user_sad_path_6(self):
        '''A method to test that a second user was not created with a similar email as the
        first user.
        '''
        self.user.users.clear()
        self.user.create_user("user1", "*****@*****.**", "password2", "password2")
        self.user.create_user("user4", "*****@*****.**", "password3", "password3")
        self.assertEqual(len(self.user.users), 1)
Пример #27
0
 def setUp(self):
     '''Creating an object of the Users class.  '''
     self.user = Users()
Пример #28
0
    @validates_schema(pass_original=True)
    def validate_schema(self, data, original):
        self.validate_permission(data, original)


class UserCreateSchema(UserSchema):
    username = fields.String(required=True)
    email = fields.String(required=True)
    password = fields.String(required=True, load_only=True)

    class Meta:
        fields = Users.get_admin_columns(Method.CREATE)


create_user_admin_serializer = ResourceUserSchema(UserCreateSchema)

create_user_serializer = ResourceUserSchema(
    UserCreateSchema, param={'only': Users.get_columns(Method.CREATE, Role.GUEST)}
)

edit_user_admin_serializer = ResourceUserSchema(UserSchema)

edit_user_profile_serializer = ResourceUserSchema(
    UserSchema, param={'only': Users.get_columns(Method.UPDATE, Role.USER)}
)

read_user_serializer = ResourceUserSchema(
    UserSchema, param={'only': Users.get_columns(Method.READ, Role.GUEST)}
)
Пример #29
0
def user():
	user_id = int(web.cookies(user_id=0).get('user_id'))
	return Users.get(user_id)
Пример #30
0
def register_user(request):
    #url = request.build_absolute_uri(None)
    #form = UserCreationForm(request.POST)

    #parsed = urlparse.parse_qs(urlparse.urlparse(url).query)
    if request.method == "POST":
        print("IS THE FORM VALID")
        form = UserCreationForm(request.POST)
        print(form)
        if form.is_valid():
            print("YES IT IS")
            data = form.cleaned_data
            userid = data['username']
            print('USERID is ', userid)
            form.save()
            #print(userid)
            if userid != None:
                print("userid not None!!")

                owner_key = request.session.get('owner_key')
                owner_secret = request.session.get('owner_secret')
                display = request.session.get('display')

                newUser = Users(user_id = userid, user_name = display, user_strength = 0,
                            user_agility = 0, user_willpower = 0, user_constitution = 0,
                            user_achievement = bin(0), token = owner_key,
                            token_secret=owner_secret, group = "None")

                newUser.save()

            return HttpResponseRedirect('/register_success')

    url = request.build_absolute_uri(None)
    parsed = urlparse.parse_qs(urlparse.urlparse(url).query)
    if(len(parsed)<1):
        client = fitbit.FitbitOauthClient(FITAPP_CONSUMER_KEY, FITAPP_CONSUMER_SECRET)
        token = client.fetch_request_token()
        request.session['token_no'] = token
        webbrowser.open(client.authorize_token_url())
        return render_to_response('register.html')

    else:
        client = fitbit.FitbitOauthClient(FITAPP_CONSUMER_KEY, FITAPP_CONSUMER_SECRET)
        token = request.session.get('token_no')
        listverifier = parsed['oauth_verifier']
        verifier = listverifier[0]
        result = client.fetch_access_token(verifier,token)
        userid = result.get('encoded_user_id')
        owner_key = result.get('oauth_token')
        owner_secret = result.get('oauth_token_secret')


        auth = fitbit.Fitbit(FITAPP_CONSUMER_KEY, FITAPP_CONSUMER_SECRET, resource_owner_key = owner_key, resource_owner_secret = owner_secret)
        profile = auth.user_profile_get(userid)
        username = profile.get('user').get('displayName')
        request.session['owner_key'] = owner_key
        request.session['owner_secret'] = owner_secret
        request.session['display'] = username

        #username = profile.get('user').get('displayName')

        '''
        newUser = Users(user_id = userid, user_name = username, user_strength = 0,
                            user_agility = 0, user_willpower = 0, user_constitution = 0,
                            user_achievement = bin(0), token = owner_key,
                            token_secret = owner_secret, group = "None")
        newUser.save()
        return HttpResponseRedirect
        '''




    return render(request,'register.html', {"userid": userid,
                                                "form" : UserCreationForm()})