Beispiel #1
0
 def logout(self):
     user = authentication.get_current_user()
     if user:
         authentication.logout(cherrypy.session)
         UserDao.delete_cookie(user.get('username'))
         self.usetCookie()
     redirect(URL_LOGIN)
Beispiel #2
0
	def post(self):
		'''登陆请求
		paras:
			*	email_or_phone 		用户可以输入手机号或者邮箱来进行登陆
			*	pwd 				登陆密码
			*	remember_me			是否记住登陆状态(TODO)
		response:

		'''
		email_or_phone = self.get_argument('email_or_phone')
		pwd = self.get_argument('pwd')
		remember_me = self.get_argument('remember_me',default='off')

		enroll_type = StringUtil.is_email_or_phone(email_or_phone)
		if enroll_type == 'neither':
			#如果用户输入不是邮箱或者电话号,则登陆失败
			self.write(RESPONSE.WRONG_TYPE)
			return
		user = UserDao.get_user_by_email(email_or_phone) if enroll_type == 'email' else UserDao.get_user_by_phone(email_or_phone)
		if not user:
			#如果取不到用户,则登陆失败
			self.write(RESPONSE.WRONG_TYPE)
		elif hashlib.md5(pwd).hexdigest() != user['pwd']:
			#如果密码错误,则登陆失败
			self.write(RESPONSE.INVALID_PASSWORD)
		else:
			self.set_secure_cookie("tid",str(user['tid']))
			self.set_secure_cookie("timestamp", str(time.time()))
			self.write(RESPONSE.SUCCESS)
Beispiel #3
0
	def post(self):
		'''用户注册
		paras:
			*	email_or_phone: 	用户可以输入自己的手机号或者邮箱用来注册
			*	user_name:			用来显示用户名称,不唯一
			*	pwd:				用户登录密码
			*	pwd_confirm:		用户登录密码确认
			*	accept:				用户是否接受使用条款
		'''
		email_or_phone = self.get_argument('email_or_phone')
		user_name = self.get_argument('user_name')
		pwd = self.get_argument('pwd')
		
		enroll_type = StringUtil.is_email_or_phone(email_or_phone)
		if enroll_type == 'neither':
			#如果用户输入不是邮箱或者电话号,则注册失败
			self.write(RESPONSE.WRONG_TYPE)
			return
		elif enroll_type == 'email':
			#如果email已经注册,则注册失败
			if UserDao.get_user_by_email(email_or_phone):
				self.write(RESPONSE.EMAIL_EXIST)
				return
		else:
			#如果手机号已经注册,则注册失败
			if UserDao.get_user_by_phone(email_or_phone):
				self.write(RESPONSE.PHONE_EXIST)
				return
		#进行用户注册流程
		UserDao.register(email_or_phone, enroll_type, user_name, pwd)
		self.write(RESPONSE.SUCCESS)
Beispiel #4
0
def get_users():
    current_user = get_current_user()
    result = []
    customers = assigneesHandler.get_customers(current_user.get('username'))
    if authentication.has_full_access(current_user):
        # super user, master admin
        result = [_set_customers(u) for u in UserDao.get_all()]
    elif authentication.user_is_master(current_user):
        if authentication.user_is_assigned_master(current_user):
            # master user (assigned master customer)
            users = [_set_customers(u) for u in UserDao.get_all()]
            result = [u for u in users if authentication.allow_semi_user_changes(u)]
        else:
            # master user (not assigned master customer)
            for customer in customers:
                assigned_users = assigneesHandler.get_assignees(customer.get('customer'))
                users = [get_user(a['user']) for a in assigned_users]
                result = result + [u for u in users if authentication.allow_semi_user_changes(u)]
    else:
        # can only be assigned to one..
        customer = customers[0]
        assigned_users = assigneesHandler.get_assignees(customer.get('customer'))
        users = [get_user(a['user']) for a in assigned_users]
        result = [u for u in users if u and authentication.allow_semi_user_changes(u)]
    return result
Beispiel #5
0
    def put(self, id):

        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, location='json')
        parser.add_argument('password', type=str, location='json')
        parser.add_argument('email', type=str, location='json')
        parser.add_argument('first_name', type=str, location='json')
        parser.add_argument('last_name', type=str, location='json')
        parser.add_argument('is_admin', type=bool, location='json')
        parser.add_argument('is_active', type=bool, location='json')
        args = parser.parse_args()

        user_dao = UserDao(self.db_session())
        user = user_dao.retrieve(id=id)
        if user is None:
            return self.error_response('User {} not found'.format(id), http.NOT_FOUND_404)

        user.username = args['username']
        if args['password'] != '':
            user.password = args['password']
        user.email = args['email']
        user.first_name = args['first_name']
        user.last_name = args['last_name']
        user.is_admin = args['is_admin']
        user.is_active = args['is_active']

        user = user_dao.save(user)

        return self.response(user.to_dict())
Beispiel #6
0
    def get(self, id):

        user_dao = UserDao(self.db_session())
        user = user_dao.retrieve(id=id)
        if user is None:
            return self.error_response('User {} not found'.format(id), http.NOT_FOUND_404)

        return self.response(user.to_dict())
Beispiel #7
0
def store_agreement(agreementData_dict):
    agreementData_dict['id'] = agreementData_dict['id'][0]
    
    if agreementData_dict['agreement'][0] == 'on':
        agreementData_dict['agreement'] = 'Y'
    else:
        agreementData_dict['agreement'] = 'N'

    UserDao.store_agreement(agreementData_dict)
Beispiel #8
0
    def delete(self, id):

        user_dao = UserDao(self.db_session())
        user = user_dao.retrieve(id=id)
        if user is None:
            return self.error_response('User {} not found'.format(id), http.NOT_FOUND_404)
        user_dao.delete(user)

        return self.response({}, http.NO_CONTENT_204)
Beispiel #9
0
def full_update_user(user):
    password = user.get('password')
    if password and password != validator.PASSWORD_PLACEHOLDER:
        set_password_salt(user)
        UserDao.update_user_with_pw_and_salt(user)
    else:
        UserDao.update_user(user)
    assigneesHandler.update_assignee(user)
    return True
Beispiel #10
0
def semi_update_user(user):
    password = user.get('password')
    old_user = get_user(user.get('username'))
    user['role'] = old_user.get('role')
    if password and password != validator.PASSWORD_PLACEHOLDER:
        set_password_salt(user)
        UserDao.update_user_with_pw_and_salt(user)
    else:
        UserDao.update_user(user)
    return True
Beispiel #11
0
def check_login(username, password):
    user_dao = UserDao(g.db_session)
    user = user_dao.retrieve(username=username)
    if user is None:
        return None, 'User {} not found'.format(username)
    if not user.is_active:
        return None, 'User {} no longer active'.format(username)
    if user.password != password:
        return None, 'Invalid password'
    return user, None
Beispiel #12
0
    def test_005_onMessage_create_user_ok(self):
        num_users_before = len(UserDao.get_all())
        user_template = testData.USER_CREATE_OK
        user_data = json.loads(user_template['data'])
        SyncManager.onMessage(user_template)
        num_users_after = len(UserDao.get_all())

        user_created = UserDao.get_user(user_data['username'])
        self.assertEquals(num_users_after, num_users_before + 1)
        self.assertEquals(user_created['username'], user_data['username'])
Beispiel #13
0
    def test_008_onMessage_delete_user_ok(self):
        user_delete = testData.USER_DELETE
        user_data = json.loads(user_delete['data'])
        user_before = UserDao.get_user(user_data['username'])
        self.assertIsNotNone(user_before)

        SyncManager.onMessage(user_delete)

        user_after = UserDao.get_user(user_data['username'])
        self.assertIsNone(user_after)
Beispiel #14
0
 def test_020_put(self):
     global cherrypy
     cherrypy.session = {'roles': ['admin', 'planner', 'driver']}
     olduser = UserDao.get_user("username")
     self.assertEqual(olduser['email'], "*****@*****.**")
     
     user.put(olduser['id'], olduser['username'], olduser['surname'], olduser['name'], olduser['number'], olduser['password'], '*****@*****.**')
     changeduser = UserDao.get_user("username")
     self.assertEqual(changeduser['name'], "name")
     self.assertEqual(changeduser['number'], "1234567890")
     self.assertEqual(changeduser['email'], "*****@*****.**")
Beispiel #15
0
    def test_012_test_user_correction_ack(self):

        user_conflict_ack = testData.USER_CORRECTION_ACK
        correction = json.loads(user_conflict_ack['correction'])
        user_before = UserDao.get_user(correction['username'])
        self.assertNotEqual(correction, user_before)

        SyncManager.onMessage(user_conflict_ack)

        user_after = UserDao.get_user(correction['username'])
        self.assertEqual(correction, user_after)
Beispiel #16
0
def test(user_ids):
	# user_ids is an array of ids []
	r = redis.Redis()
	user_dao = UserDao(r)
	
	for user in user_ids:
		got_user = user_dao.get_user(user)
		print "Here's a user..."
		print got_user.screenname
		print got_user.id
		print got_user.oauth_token_secret
		print got_user.oauth_token
		print "-end-"
Beispiel #17
0
def delete_user(username):
    user = UserDao.get_user(username)
    if user and authentication.allow_full_user_changes(username):
        UserDao.delete_user(username)
    user = UserDao.get_user(username)
    if not user:
        assignees = assigneesHandler.get_customers(username)
        for assignee in assignees:
            assigneesHandler.delete(assignee.get('user'), assignee.get('customer'))
        assignees = assigneesHandler.get_customers('username')
        if not assignees or len(assignees) == 0:
            return True
    return False
Beispiel #18
0
def init_tables():
    user_dao = UserDao(db.session)
    for item in app.config['USERS']:
        user = user_dao.retrieve(username=item['username'])
        if user is None:
            user_dao.create(username=item['username'],
                            password=item['password'],
                            email=item['email'],
                            first_name=item['first_name'],
                            last_name=item['last_name'],
                            is_superuser=item['is_superuser'],
                            is_admin=item['is_admin'],
                            is_active=item['is_active'],
                            is_visible=item['is_visible'])
Beispiel #19
0
 def insertUserJson(self, json):
     accounttypenumber = json['AccountTypeNumber']
     firstname = json['FirstName']
     lastname = json['LastName']
     phone = json['Phone']
     email = json['Email']
     majornumber = json['MajorNumber']
     aboutme = json['AboutMe']
     yearofenrollment = json['YearofEnrollment']
     creationdate = json['CreationDate']
     lastlogin = json['LastLogin']
     status = json['Status']
     if accounttypenumber and firstname and lastname and phone and email and majornumber and aboutme and yearofenrollment and creationdate and lastlogin and status:
         dao = UserDao.UserDAO()
         userid = dao.insert(accounttypenumber, firstname, lastname, phone,
                             email, majornumber, aboutme, yearofenrollment,
                             creationdate, lastlogin, status)
         result = self.build_users_attributes(userid, accounttypenumber,
                                              firstname, lastname, phone,
                                              email, majornumber, aboutme,
                                              yearofenrollment,
                                              creationdate, lastlogin,
                                              status)
         return jsonify(Users=result), 201
     else:
         return jsonify(Error="Unexpected attributes in post request"), 400
Beispiel #20
0
    def post(self):

        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, required=True, location='json')
        parser.add_argument('password', type=str, required=True, location='json')
        parser.add_argument('email', type=str, required=True, location='json')
        parser.add_argument('first_name', type=str, location='json')
        parser.add_argument('last_name', type=str, location='json')
        parser.add_argument('is_admin', type=bool, location='json')
        parser.add_argument('is_active', type=bool, location='json')
        args = parser.parse_args()

        user_dao = UserDao(self.db_session())
        user = user_dao.create(**args)

        return self.response(user.to_dict(), http.CREATED_201)
Beispiel #21
0
    def get(self):

        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, location='args')
        parser.add_argument('email', type=str, location='args')
        parser.add_argument('first_name', type=str, location='args')
        parser.add_argument('last_name', type=str, location='args')
        parser.add_argument('is_admin', type=bool, location='args')
        parser.add_argument('is_active', type=bool, location='args')
        args = parser.parse_args()

        user_dao = UserDao(self.db_session())
        users = user_dao.retrieve_all(**args)
        result = [user.to_dict() for user in users]

        return self.response(result)
Beispiel #22
0
 def deleteUser(self, userid):
     dao = UserDao.UserDAO()
     if not dao.getUserById(userid):
         return jsonify(Error="User not found."), 404
     else:
         dao.delete(userid)
         return jsonify(DeleteStatus="OK"), 200
Beispiel #23
0
def get_group_list():
    request_params = loadParams()
    if request_params.has_key('userID'):
        data = UserDao.query_group_list(request_params['userID'])
        return parseResponse(0, data)
    else:
        return parseResponse(-1)
Beispiel #24
0
def deal_login(json_data):
    flag = UserDao.check_user_info(json_data['user_name'], json_data['user_password'])

    if not flag:
        print("No user info or wrong password")

    return flag
Beispiel #25
0
 def updateUserJson(self, userid, json):
     dao = UserDao.UserDAO()
     if not dao.getUserById(userid):
         return jsonify(Error="Admin not found."), 404
     else:
         accounttypenumber = json['AccountTypeNumber']
         firstname = json['FirstName']
         lastname = json['LastName']
         phone = json['Phone']
         email = json['Email']
         majornumber = json['MajorNumber']
         aboutme = json['AboutMe']
         yearofenrollment = json['YearofEnrollment']
         creationdate = json['CreationDate']
         lastlogin = json['LastLogin']
         status = json['Status']
         if accounttypenumber and firstname and lastname and phone and email and majornumber and aboutme and yearofenrollment and creationdate and lastlogin and status:
             dao.update(accounttypenumber, firstname, lastname, phone,
                        email, majornumber, aboutme, yearofenrollment,
                        creationdate, lastlogin, status)
             result = self.build_users_attributes(userid, accounttypenumber,
                                                  firstname, lastname,
                                                  phone, email, majornumber,
                                                  aboutme, yearofenrollment,
                                                  creationdate, lastlogin,
                                                  status)
             return jsonify(Users=result), 200
Beispiel #26
0
    def delete(self, id, user_id):

        user_group_dao = UserGroupDao(self.db_session())
        user_group = user_group_dao.retrieve(id=id)
        if user_group is None:
            return self.error_response('User group {} not found'.format(id), http.NOT_FOUND_404)

        user_dao = UserDao(self.db_session())
        user = user_dao.retrieve(id=user_id)
        if user is None:
            return self.error_response('User {} not found'.format(id), http.NOT_FOUND_404)

        if user in user_group.users:
            user_group.users.remove(user)
            user_group = user_group_dao.save(user_group)

        return self.response(user_group.to_dict())
Beispiel #27
0
 def getAllUsers(self):
     dao = UserDao.UserDAO()
     users_list = dao.getAllUsers()
     result_list = []
     for row in users_list:
         result = self.build_users_dict(row)
         result_list.append(result)
     return jsonify(Users=result_list)
Beispiel #28
0
def check_token(token):
    if 'SECRET_KEY' not in g.config.keys():
        return None, 'Could not retrieve secret key'
    secret = g.config['SECRET_KEY']
    if secret is None:
        return None, 'Secret key is empty'
    try:
        data = jwt.decode(token, secret, algorithms=['HS256'])
    except JWTError as e:
        return None, 'Could not decode token ({})'.format(e.message)
    user_dao = UserDao(g.db_session)
    user = user_dao.retrieve(id=data['id'])
    if user is None:
        return None, 'User {} not found'.format(data['id'])
    if not user.is_active:
        return None, 'User {} no longer active'.format(user.username)
    return user, None
Beispiel #29
0
 def getUserById(self, UserID):
     dao = UserDao.UserDAO()
     row = dao.getUserById(UserID)
     if not row:
         return jsonify(Error="User Not Found"), 404
     else:
         users = self.build_users_dict(row)
         return jsonify(Users=users)
Beispiel #30
0
 def getUserAccountFromSql(self, userInfo):
     userAccountCheck = UserAccountCheck.UserAccountCheck()
     userDao = UserDao.UserDao()
     userAccountCheck = userDao.getUserAccountCheckFromSql(userInfo)
     userAccountCheck.assetAddress = list(
         userAccountCheck.assetAddress.split(","))
     userAccountCheck.assetAddress.sort()
     return userAccountCheck
Beispiel #31
0
    def test_010_test_not_accept_user_update(self):

        user_update_conflict = testData.USER_UPDATE_CONFLICT
        user_conflict_data = json.loads(user_update_conflict['data'])
        user_conflict_prev = json.loads(user_update_conflict['prev'])
        user_before = UserDao.get_user(user_conflict_data['username'])
        self.assertNotEqual(user_before, user_conflict_prev)

        config.LOCAL = True

        SyncManager.send_correction_ack = MagicMock(return_value="ok")
        SyncManager.onMessage(user_update_conflict)

        user_after = UserDao.get_user(user_conflict_data['username'])

        self.assertEqual(user_before, user_after)
        SyncManager.send_correction_ack.assert_called_with(user_update_conflict['id'], user_update_conflict['burner_sn'], user_before)
Beispiel #32
0
    def test_007_onMessage_update_user_ok(self):
        user_update = testData.USER_UPDATE
        config.LOCAL = False
        user_before = UserDao.get_user(json.loads(user_update['data'])['username'])
        SyncManager.onMessage(user_update)
        user_after = UserDao.get_user(json.loads(user_update['data'])['username'])

        self.assertNotEquals(user_before['email'], user_after['email'])
        self.assertNotEquals(user_before['surname'], user_after['surname'])
        self.assertNotEquals(user_before['name'], user_after['name'])
        self.assertNotEquals(user_before['phone'], user_after['phone'])
        self.assertNotEquals(user_before['password'], user_after['password'])
        self.assertNotEquals(user_before['salt'], user_after['salt'])

        self.assertEquals(user_before['role'], user_after['role'])
        self.assertEquals(user_before['username'], user_after['username'])
        self.assertEquals(user_before['burner_sn'], user_after['burner_sn'])
Beispiel #33
0
class UserService:
    def __init__(self):
        self.__user_dao = UserDao()

    def add_user(self, user_id, name, email, phone):

        existing_user = self.__user_dao.get_user(user_id)
        if existing_user:
            existing_user.set_name(name)
            existing_user.set_email(email)
            existing_user.set_phone(phone)
            self.__user_dao.update_user(existing_user)
        else:
            new_user = User(user_id, name, email, phone)
            self.__user_dao.add_user(new_user)

    def get_user(self, user_id):
        return self.__user_dao.get_user(user_id)

    def show_user(self, user_id):

        user = self.__user_dao.get_user(user_id)
        collect_from = user.get_payment_from()
        for u in collect_from:
            print(f'{u} owes {user_id}: {collect_from[u]}')

        paid_to = user.get_payment_to()
        for u in paid_to:
            print(f'{user_id} owes {u}: {paid_to[u]}')

        print('--------------------------------------')
Beispiel #34
0
def dumpdata():
	json_file = open('fixtures/fakers.json', 'r')
	json_string = ''
	for line in json_file:
		json_string += line
	fake_data = json.loads(json_string)
	
	# dump to redis
	r = redis.Redis()
	user_ids = []
	for faker in fake_data:
		user = User(faker['screen_name'], faker['user_id'], oauth_token_secret=faker['oauth_token_secret'], oauth_token=faker['oauth_token'])
		user_dao = UserDao(r)
		user_id = user_dao.save(user)
		user_ids.append(user_id)
		
	# test DAO get
	test(user_ids)
Beispiel #35
0
def resp(token, did):
	user = UserDao.get_user_by_token(token)
	if not user: return RESPONSE.WRONG_TOKEN
	devices = DeviceDao.get_devices_by_user(user)
	for device in devices:
		if device['did'] == did:
			#TODO 需要进行一些数据清理工作
			return RESPONSE.SUCCESS
	return RESPONSE.WRONG_DID
Beispiel #36
0
def user_management():
    """
    用户管理(增加、删除、更新)
    :return: 
    """
    request_params = loadParams()
    if request_params.has_key('action') and request_params.has_key('user'):
        action = request_params['action']
        user_info = request_params['user']
        pass
    else:
        return parseResponse(10000000)
    user = User()
    for key in user_info:
        if hasattr(user, key):
            setattr(user, key, user_info[key])
    UserDao.user_management(int(action), user)
    return parseResponse(0)
Beispiel #37
0
 def test_010_post(self):
     global cherrypy
     cherrypy.session = {'roles': ['admin', 'planner', 'driver']}
     user.post("username", "surname", "name", "1234567890", "password", "*****@*****.**")
     createduser = UserDao.get_user("username")
     self.assertEqual(createduser['name'], "name")
     self.assertEqual(createduser['number'], "1234567890")
     self.assertEqual(createduser['username'], "username")
     self.assertEqual(createduser['role'], "user")
Beispiel #38
0
 def updateAsset(self, to):
     userDao = UserDao.UserDao()
     assetAddressArray = to.assetAddress.split(",")
     for assetAddress in assetAddressArray:
         to.assetAddress = assetAddress
         usertAssetObject = UserAsset.UserAsset()
         usertAssetObject = to
         userDao.updateAsset(usertAssetObject)
     pass
Beispiel #39
0
def get_user(username=None):
    current_user = get_current_user()
    if not username:
        return current_user
    else:
        user = UserDao.get_user(username)
        if user:
            user = _set_customers(user)
            if authentication.allow_semi_user_changes(user):
                return user
Beispiel #40
0
def modify_user(payload):
    try:
        result = UserDao.check_email_gamertag_duplication(payload['id'], payload['email'], payload['gamertag'])

        if result:
            return MessageService.user_info_duplication

        if check_fields_existance_in_payload(payload, 'id', 'first_name', 'last_name', 'email', 'address', 'gamertag',
                                             'profile_picture'):
            user = UserDao.update_user(payload)
            if user:
                return MessageService.generate_success_message('', user.to_dictionary())
            else:
                MessageService.generate_custom_message('No user was found', {})
        else:
            return MessageService.missing_fields_request

    except Exception as e:
        return MessageService.generate_internal_server_error(e)
Beispiel #41
0
def test_enroll():
	user = UserDao.get_user_by_email(email)
	device = user['device']
	active_code = ""
	for d in device:
		if d['uid'] == uid:
			active_code = d['active_code']
	tid = user['tid']

	result = DeviceDao.enroll(uid,active_code,tid)
	assert result['status'] == 1
Beispiel #42
0
def verify_password():
    """
    密码校验
    :return: 
    """
    request_params = loadParams()
    is_success = UserDao.verify_password(request_params)
    if is_success:
        return parseResponse(0)
    else:
        return parseResponse(-1)
Beispiel #43
0
def check_password(username, password):
    user = UserDao.get_user(username)
    if user is None:
        LOG.warning("Failed logon attempt fort " + str(username))
        return False
    salt = user["salt"]
    hashed_password = hashlib.sha512(password.encode("utf-8") + salt.encode("utf-8")).hexdigest()
    if user and username == user["username"] and hashed_password == user["password"]:
        return user
    else:
        LOG.warning("Failed logon attempt for " + str(username))
        return False
Beispiel #44
0
class UserService:
    def __init__(self):
        self.user_dao = UserDao()

    def insert_user(self, name, email, country):

        existing_user = self.user_dao.get_user(email)
        if existing_user:
            existing_user.set_name(name)
            existing_user.set_country(country)
            return self.user_dao.update_user(existing_user)
        else:
            user = User(uuid.uuid4(), name, email, country)
            return self.user_dao.add_user(user)

    def insert_score(self, email, score):

        existing_user = self.user_dao.get_user(email)
        if not existing_user:
            raise UserNotExist
        else:
            existing_user.set_score(score)
            return self.user_dao.update_user(existing_user)

    def search_user(self, search_criteria):
        return self.user_dao.search_user(search_criteria)
Beispiel #45
0
 def newIssue(self, bossAccount, amount):
     userDao = UserDao.UserDao()
     issueObject = IssueObject.IssueObject()
     issueObject.amount = amount
     issueObject.createUserAccountAddress = bossAccount.address
     issueObject.sourceId = "wsy_qian_yi_zhuan_yong_bao_wen"
     issueObject.content = "{\"wsy\":\"wsy_qian_yi_zhuan_yong_bao_wen\"}"
     issueObject.unit = "wsy_qian_yi_zhuan_yong_bao_wen"
     jsonResult = userDao.issue(issueObject)
     userAsset = UserAsset.UserAsset()
     userAsset.assetAddress, userAsset.status, userAsset.userAddress, userAsset.money, userAsset.sourceId = \
     jsonResult['assetId'], "0", bossAccount.address, amount, issueObject.sourceId
     return userAsset
Beispiel #46
0
    def cookie(self):
        request_cookie = cherrypy.request.cookie
        cookie_val = request_cookie.get(COOKIE_NAME).value.split('|')

        if len(cookie_val) == 2:
            username, cookie_id = cookie_val
            user = UserDao.get_user(username)

            if user.get('cookie_id') and user.get('cookie_expire'):
                if user['cookie_id'] == cookie_id and datetime_to_unix(user.get('cookie_expire')) > time.time():
                    authentication.login(cherrypy.session, user)
                    return OkResponse('ok')
        return ConflictResponse('error')
Beispiel #47
0
    def login(self, username=None, password=None, remember_me=False):
        print(remember_me)
        if username and password:
            user = authentication.check_password(username, password)
            if user:
                user = authentication.login(cherrypy.session, user)

                if remember_me:
                    username, cookie_id = user.get('username'), uuid.uuid4().hex
                    self.setCookie( "%s|%s" % (username, cookie_id))
                    cookie_expire_timestamp = datetime.datetime.fromtimestamp(COOKIE_EXPIRE).strftime('%Y-%m-%d %H:%M:%S')
                    UserDao.update_cookie_id(cookie_id, cookie_expire_timestamp, username)

                self.index();
            else:
                try:
                    self.unsetCookie()
                except:
                    pass
                redirect('/login.html?failed=true')
        else:
            redirect(URL_LOGIN)
Beispiel #48
0
def update(token,did,loc_info):
	user = UserDao.get_user_by_token(token)
	if not user: return {'status':0, 'desc':'wrong token'}
	device_loc = LocCollection.find_one({'did':did})
	if device_loc:
		device_loc['loc_info'].append(loc_info)
	else:
		device_loc = {
			'did':did,
			'loc_info': loc_info
		}
	LocCollection.update({'did':did}, device_loc, upsert=True)
	return {'status':1}
Beispiel #49
0
def new_user(user):
    msg = []
    username_exists = userDao.username_exists(user.get('username'))
    if username_exists:
        msg.append(KEY_USERNAME_TAKEN)

    if PASSWORD_KEY not in user:
        msg.append(KEY_INVALID_PASSWORD)

    error_msg = valid_user(user)
    if len(error_msg):
        msg += error_msg
    return msg
Beispiel #50
0
def get_user_permission():
    request_params = loadParams()
    if request_params.has_key('userId'):
        userId = request_params['userId']
        pass
    if request_params.has_key('type'):
        type = request_params['type']
        pass
    if userId is None or type is None:
        return parseResponse(-1)
    else:
        data = UserDao.query_user_permission(userId, type)
        return parseResponse(0, data)
Beispiel #51
0
def pull(token, did):
	user = UserDao.get_user_by_token(token)
	if not user: return RESPONSE.WRONG_TOKEN
	devices = DeviceDao.get_devices_by_user(user)
	for device in devices:
		if device['did'] == did:

			#TODO 需要将具体的信息返回回去
			RESPONSE.PULL_SUCCESS['data'] = device['pull_info']
			device['pull_info']=[]
			UserCollection.update({'token':user['token']},user)
			return RESPONSE.PULL_SUCCESS
	return RESPONSE.WRONG_DID
Beispiel #52
0
def get_all_users():
    try:
        result = UserDao.get_users()
        response = []
        for user in result:
            response.append(user.to_dictionary())

        if len(response):
            return MessageService.generate_success_message('', response)
        else:
            return MessageService.generate_custom_message('No users were found', {})

    except Exception as e:
        return MessageService.generate_internal_server_error(e)
Beispiel #53
0
def initial(token,phone,did,cid,imei):
	user = UserDao.get_user_by_token(token)
	if not user: return RESPONSE.WRONG_TOKEN
	devices = DeviceDao.get_devices_by_user(user)
	for device in devices:
		if device['phone'] == phone:
			device['did'] = did
			device['cid'] = cid
			device['imei'] = imei
			UserCollection.update({'tid':user['tid']},user)
			#TODO 需要增加client对初始化配置信息
			RESPONSE.INITIAL_SUCCESS['initial'] = {}
			return RESPONSE.INITIAL_SUCCESS
	return RESPONSE.WRONG_PHONE
Beispiel #54
0
def remove_user(payload):
    try:
        if check_fields_existance_in_payload(payload, 'id'):
            user = UserDao.delete_user(payload['id'])

            if user:
                return MessageService.generate_success_message('', user.to_dictionary())
            else:
                return MessageService.generate_custom_message('No user was found', {})
        else:
            return MessageService.missing_fields_request

    except Exception as e:
        return MessageService.generate_internal_server_error(e)
Beispiel #55
0
 def bassCreateUser(self, username, userId):
     user = UserInfo.UserInfo()
     user.name = username
     user.id = userId
     user = user.__dict__
     # 打印字典
     print(user)
     # 字典转化为json
     userJson = json.dumps(user)
     userDao = UserDao.UserDao()
     userDict = userDao.baasCreateUser(userJson)
     userInfo = UserInfo.UserInfo()
     userInfo.userId, userInfo.publicKey, userInfo.privateKey, userInfo.address = userDict[
         "id"], userDict['basePublicKey'], userDict[
             'basePrivateKey'], userDict['baseAccountAddress']
     return userInfo
Beispiel #56
0
def create_user(user):
    customers = user.get('customers')
    result = True
    for customer_id in customers:
        if not authentication.allow_changes(customer_id):
            result = False
            break
    if result:
        msg = validator.new_user(user)
        if not msg:
            set_password_salt(user)
            res = UserDao.create_user(user)
            res = assigneesHandler.update_assignee(user)
            return True
        else:
            return msg
Beispiel #57
0
def login(payload):
    if not check_fields_existance_in_payload(payload, 'email', 'password'):
        return MessageService.missing_fields_request

    try:
        result = UserDao.login_user(payload)

        if not result:
            return MessageService.authentication_failed

        token = AuthService.generate_token(result)
        data = {'token': 'Bearer ' + token}

        return MessageService.generate_success_message('', data)

    except Exception as e:
        return MessageService.generate_internal_server_error(e)
Beispiel #58
0
def enroll(tid, active_code, phone):
	user = UserDao.get_user_by_tid(tid)
	if not user: return RESPONSE.WRONG_TID
	devices = DeviceDao.get_devices_by_user(user)
	for device in devices:
		if device['phone'] == phone:
			if device['active_code'] == active_code:
				if device['active'] == True: 
					return RESPONSE.ALREADY_ACTIVED
				device['active'] = True
				UserCollection.update({'tid':user['tid']},user)
				RESPONSE.ENROLL_SUCCESS['token'] = user['token']
				print RESPONSE.ENROLL_SUCCESS['token'] 
				return RESPONSE.ENROLL_SUCCESS
			else:
				return RESPONSE.WRONG_ACTIVE_CODE
	return RESPONSE.WRONG_PHONE
Beispiel #59
0
def test_register_list():
	user = UserDao.get_user_by_email(email)
	list1 = DeviceDao.register_list(user)
	assert list1 != []
Beispiel #60
0
def test_exist():
	user = UserDao.get_user_by_email(email)
	device = DeviceDao.exist(uid,owner,user)
	assert device == True