Пример #1
0
    def GET(self):
        username = web.input().get('u')
        adminpush = web.input().get('p')

        if username and adminpush != None:  #用于管理员测试
            #搜索自动处理的feed(字符串http开头)
            feeds = []
            #搜索手动处理的feed
            mfeeds = []
            feeds_num = 0
            ownfeeds = model.username2feeds(username)
            if len(ownfeeds) != 0:
                '''
				#取feeds信息
				books = (model.get_allbooks())
				for book in books:
					if book.f_id in ownfeeds:
						b=[]
						if cmp('http',book.url[0:4].lower()) == 0:
							b.append(book.title)
							b.append(book.url)
							if book.isfulltext == 1:
								b.append(True)
							else:
								b.append(False)
							feeds.append(b)
						else:
							b.append(book.url)
							mfeeds.append(b)
						feeds_num += 1
				#取用户信息
				user = model.getuser(username)[0]
				#加入eq
				if user and user.kindle_email:
					jobq.enqueue(pushwork,args=(user.kindle_email,feeds,mfeeds,user.keep_image),timeout=feeds_num*300)
				'''
                user = model.getuser(username)[0]
                if user and user.kindle_email:
                    jobq.enqueue(pushwork3,
                                 args=(user.kindle_email, ownfeeds,
                                       user.keep_image, user.ifmobi))
            return jjenv.get_template("autoback.html").render(
                nickname=session.username,
                title='Delivering',
                tips='admin已投递!')
        else:
            user = model.getuser(username)[0]
            if user and user.kindle_email:
                ROOT = path.dirname(path.abspath(__file__))
                output_dir = path.join(ROOT, 'templates2')
                mobi_file = path.join(output_dir, 'WelcomeRedKindle.mobi')
                jobq.enqueue(send_mail,
                             args=(SrcEmail, user.kindle_email, mobi_file, 1))
            return jjenv.get_template("autoback.html").render(
                nickname=session.username, title='Delivering', tips='已投递!')
Пример #2
0
	def GET(self):
		username = web.input().get('u')
		adminpush = web.input().get('p')

		if username and adminpush != None:#用于管理员测试
			#搜索自动处理的feed(字符串http开头)
			feeds = []
			#搜索手动处理的feed
			mfeeds = []
			feeds_num = 0
			ownfeeds = model.username2feeds(username)
			if len(ownfeeds) != 0:
				'''
				#取feeds信息
				books = (model.get_allbooks())
				for book in books:
					if book.f_id in ownfeeds:
						b=[]
						if cmp('http',book.url[0:4].lower()) == 0:
							b.append(book.title)
							b.append(book.url)
							if book.isfulltext == 1:
								b.append(True)
							else:
								b.append(False)
							feeds.append(b)
						else:
							b.append(book.url)
							mfeeds.append(b)
						feeds_num += 1
				#取用户信息
				user = model.getuser(username)[0]
				#加入eq
				if user and user.kindle_email:
					jobq.enqueue(pushwork,args=(user.kindle_email,feeds,mfeeds,user.keep_image),timeout=feeds_num*300)
				'''
				user = model.getuser(username)[0]
				if user and user.kindle_email:
					jobq.enqueue(pushwork3,args=(user.kindle_email,ownfeeds,user.keep_image,user.ifmobi))
			return jjenv.get_template("autoback.html").render(nickname=session.username,title='Delivering',tips='admin已投递!')
		else:
			user = model.getuser(username)[0]
			if user and user.kindle_email:
				ROOT = path.dirname(path.abspath(__file__))
				output_dir = path.join(ROOT, 'templates2')
				mobi_file = path.join(output_dir,'WelcomeRedKindle.mobi')
				jobq.enqueue(send_mail,args=(SrcEmail,user.kindle_email,mobi_file,1))
			return jjenv.get_template("autoback.html").render(nickname=session.username,title='Delivering',tips='已投递!')
Пример #3
0
 def post(self):
     form = self.form_loader()
     if not self.form_validate(form):
         return
     user = getuser(email=form.email.data)
     self.login(user)
     self.redirect()
Пример #4
0
def kf_randomkey_signout():
    if request.is_json:
        data = request.json
        Randomkey = password.CreateSalt(length=8)
        authid = data.get("authid")
        user_result = model.getuser(data['username'])
        if not user_result:
            raise Exceptions.InvalidCredentials()
        salt = user_result.passwordsalt
        if user_result:
            IReturn = {
                "authId": authid,
                "HashKey": Randomkey,
                "username": user_result.email,
                "salt": salt
            }
            cache_secureauth.set(authid, {
                "HashKey": Randomkey,
                "username": user_result.email,
                "salt": salt,
                "VerifyValue": user_result.password,
                "authId": authid,
                "inorderto": "signout"
            }, ttl=30)
            print(RandomKey, salt, authid)
            return Response(json.dumps(IReturn), mimetype='application/json; charset=utf-8')
        else:
            return Response(status=403)
Пример #5
0
 def post(self):
     form = self.form_loader()
     if not self.form_validate(form):
         return
     user = getuser(email=form.email.data)
     self.login(user)
     self.redirect()
Пример #6
0
	def POST(self):
		name = web.input().get('u')
		passwd = web.input().get('p')

		#检查是否已存在,格式问题
		if name.strip() == '' or passwd.strip() == '':
			tips = "不能为空!"
			return jjenv.get_template("register.html").render(nickname='',title='Register',tips=tips)
		elif len(name) > 50:
			tips = "地址太长!"
			return jjenv.get_template("register.html").render(nickname='',title='Register',tips=tips,username=name)
		elif '<' in name or '>' in name or '&' in name:
			tips = "含有非法字符!"
			return jjenv.get_template("register.html").render(nickname='',title='Register',tips=tips)

		u = model.getuser(name)
		if u:
			return jjenv.get_template("register.html").render(nickname='',title='Register',tips="用户已存在!")
		#注册
		model.input_user(name,hashlib.md5(passwd).hexdigest())

		#返回登录界面
		#raise web.seeother(r'/')

		#注册成功直接登录
		pwdhash = hashlib.md5(passwd).hexdigest()
		if model.isuser(name,pwdhash) == 1:
			session.login = 1
			session.username = name
			raise web.seeother(r'/')
		else:
			return jjenv.get_template("register.html").render(nickname='',title='Register',tips="")
Пример #7
0
    def POST(self):
        name = web.input().get('u')
        passwd = web.input().get('p')

        #检查是否已存在,格式问题
        if name.strip() == '' or passwd.strip() == '':
            tips = "不能为空!"
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips=tips)
        elif len(name) > 35:
            tips = "地址太长!"
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips=tips,
                                                              username=name)
        elif '<' in name or '>' in name or '&' in name:
            tips = "含有非法字符!"
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips=tips)

        u = model.getuser(name)
        if u:
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips="用户已存在!")
        #注册
        model.input_user(name, hashlib.md5(passwd).hexdigest())

        #返回登录界面
        raise web.seeother(r'/')
Пример #8
0
	def GET(self):
		username = web.input().get('u')
		if username:
			#搜索自动处理的feed(字符串http开头)
			feeds = []
			#搜索手动处理的feed
			mfeeds = []
			ownfeeds = model.username2feeds(username)
			if len(ownfeeds) != 0:
				#取feeds信息
				books = (model.get_allbooks())
				for book in books:
					if book.f_id in ownfeeds:
						b=[]
						if cmp('http',book.url[0:4].lower()) == 0:
							b.append(book.title)
							b.append(book.url)
							if book.isfulltext == 1:
								b.append(True)
							else:
								b.append(False)
							feeds.append(b)
						else:
							b.append(book.url)
							mfeeds.append(b)
				#取用户信息
				user = model.getuser(username)[0]
				#加入eq
				if user and user.kindle_email:
					jobq.enqueue(pushwork,user.kindle_email,feeds,mfeeds,user.keep_image)
			return jjenv.get_template("autoback.html").render(nickname=session.username,title='Delivering',tips='books put to queue!')
Пример #9
0
def kf_search_user_email(email):
    result = model.getuser(email)
    if not result:
        return Response(json.dumps({
            "error": "WrongArgs",
            "errorMessage": "错误的参数"
        }), mimetype='application/json; charset=utf-8', status=403)
    return Response(json.dumps({"uuid": result.uuid}), mimetype='application/json; charset=utf-8')
Пример #10
0
 def get_current_user(self):
     cookie = self.get_secure_cookie('user')
     if not cookie:
         return None
     user_id = int(json.loads(cookie)['id'])
     user = getuser(id=user_id)
     if user:
         return user
Пример #11
0
def name_validate(self, field):
    if not field.data:
        return
    if utils.special_char(field.data):
        raise ValidationError(u'昵称里面不允许有特殊字符。')
    user = getuser(name=field.data)
    if user and user is not self.current_user:
        raise ValidationError(u'Opps,这个昵称已经有人在用了。')
Пример #12
0
 def post(self):
     try:
         form = self.form_loader()
     except RuntimeError:
         return
     user = getuser(email = form.email.data)
     self.login(user)
     self.redirect('/')
Пример #13
0
 def get_current_user(self):
     cookie = self.get_secure_cookie('user')
     if cookie:
         user_json = json.loads(cookie)
         user = getuser(user_json['id'])
         if user:
             return user
     return False
Пример #14
0
 def get_current_user(self):
     cookie = self.get_secure_cookie('user')
     if cookie:
         user_json = json.loads(cookie)
         user = getuser(user_json['id'])
         if user:
             return user
     return False
Пример #15
0
def kf_login_verify():
    if request.is_json:
        data = request.json
        Data = cache_secureauth.get(data.get("authId"))
        if not Data:
            return Response(status=403)
        else:
            user_result = model.getuser(Data['username'])
            if user_result:
                AuthRequest = password.crypt(
                    user_result.password, Data['HashKey'])
                print(AuthRequest)
                if AuthRequest == data['Password']:
                    if Data.get("inorderto") == "signin":
                        notDoubleProfile = False
                        Profileresult = model.getprofile_createby(
                            user_result.uuid)
                        if len(Profileresult) == 1:
                            notDoubleProfile = True
                            SelectedProfile = model.format_profile(
                                Profileresult.get())

                        AccessToken = str(uuid.uuid4()).replace("-", "")
                        ClientToken = str(uuid.uuid4()).replace("-", "")

                        cache_token.set(AccessToken, {
                            "clientToken": ClientToken,
                            "bind": Profileresult.get().uuid if notDoubleProfile else None,
                            "user": user_result.uuid,
                            "group": "global",
                            "createTime": int(time.time())
                        }, ttl=config.TokenTime.RefrushTime * config.TokenTime.TimeRange)
                        IReturn = {
                            "accessToken": AccessToken,
                            "clientToken": ClientToken,
                        }
                        cache_secureauth.delete(data['authId'])
                        if data.get("requestUser"):
                            IReturn['metadata'] = {
                                "user": {
                                    "userId": user_result.uuid
                                }
                            }
                        return Response(json.dumps(IReturn), mimetype='application/json; charset=utf-8')
                    if Data.get("inorderto") == "signout":
                        result = Token.getalltoken(user_result)
                        if result:
                            for i in result:
                                cache_secureauth.delete(i)
                        return Response(status=204)
                else:
                    cache_secureauth.delete(data['authId'])
                    raise Exceptions.InvalidCredentials()
            else:
                cache_secureauth.delete(data['authId'])
                return Response(status=403)
Пример #16
0
 def secret_get(self, key):
     '''Give secret key, return user'''
     try:
         user_id = int(self.redis.get("%s:user_id"%key))
     except TypeError: # not get value.
         return None
     try:
         return getuser(id = user_id)
     except KeyError:
         return None
Пример #17
0
def quest():
    data = request.json
    '''
    if decrypt(data.get("password")) == data.get("verify"):
        return Response(status=204)
    else:
        return Response(status=403)
    '''
    if not re.match(utils.StitchExpression(config.reMatch.UserEmail),
                    data.get("email")):
        raise Exceptions.IllegalArgumentException()  # 邮箱不匹配
    if not re.match(utils.StitchExpression(config.reMatch.UserPassword),
                    decrypt(data.get("password"))):
        raise Exceptions.InvalidToken()  # 密码不合格
    if not re.match(utils.StitchExpression(config.reMatch.PlayerName),
                    data.get("username")):
        raise Exceptions.InvalidCredentials()  # 名称不合格
    if model.getuser(data.get("email")):
        raise Exceptions.DuplicateData()  # 已注册的用户

    if not cache_limit.get(data.get("email")):
        cache_limit.set(data.get("email"), "LIMITER", ttl=180)
    else:
        cache_limit.set(data.get("email"), "LIMITER", ttl=180)
        return Response(json.dumps({
            "error":
            "ForbiddenOperationException",
            "errorMessage":
            "Frequency limit, wait a moment."
        }),
                        status=403,
                        mimetype='application/json; charset=utf-8')

    password = decrypt(data.get("password"))
    salt = utils.CreateSalt(length=16)
    registerId = str(uuid.uuid4()).replace("-", "")

    cache_verify.set(registerId, {
        "email": data.get("email"),
        "password": {
            "context": password,
            "salt": salt
        },
        "username": data.get("username")
    },
                     ttl=60 * 30)
    mail = template_mail.copy()
    mail["content_text"] = mail["content_text"].format(REGISTER_URL=("".join([
        config.HostUrl, "/api/knowledgefruits/register/verify?registerId=",
        registerId
    ])))
    mailer.send_mail(data.get("email"), mail)

    return Response(status=204)
Пример #18
0
    def POST(self):
        name = web.input().get('u')
        passwd = web.input().get('p')

        #检查是否已存在,格式问题
        if name.strip() == '' or passwd.strip() == '':
            tips = "不能为空!"
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips=tips)
        elif '@' not in name or '.' not in name == '':
            tips = "地址有误!"
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips=tips)
        elif len(name) > 50:
            tips = "地址太长!"
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips=tips,
                                                              username=name)
        elif '<' in name or '>' in name or '&' in name:
            tips = "含有非法字符!"
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips=tips)
        elif len(passwd.strip()) < 4:
            tips = "密码太短!"
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips=tips)

        u = model.getuser(name)
        if u:
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips="用户已存在!")
        #注册
        model.input_user(name, hashlib.md5(passwd).hexdigest())

        #返回登录界面
        #raise web.seeother(r'/')

        #注册成功直接登录
        pwdhash = hashlib.md5(passwd).hexdigest()
        if model.isuser(name, pwdhash) == 1:
            session.login = 1
            session.username = name
            raise web.seeother(r'/')
        else:
            return jjenv.get_template("register.html").render(nickname='',
                                                              title='Register',
                                                              tips="")
Пример #19
0
def kf_user_changepasswd(username):
    if request.is_json:
        data = request.json
        user_result = model.getuser(username)
        if user_result:
            AccessToken = data['accessToken']
            ClientToken = data['clientToken'] if 'clientToken' in data else None
            if not ClientToken:
                token_result_boolean = model.is_validate(AccessToken)
                token = model.gettoken(AccessToken)
            else:
                token_result_boolean = model.is_validate(
                    AccessToken, ClientToken)
                token = model.gettoken(AccessToken, ClientToken)
            if token_result_boolean and token:
                # 如果Token有效
                # 开始解析由公钥(/api/yggdrasil)加密的东西
                # 这玩意是个base64
                encrypt = base64.b64decode(data['Password'])
                decrypt_errorMessage = password.decrypt(
                    encrypt, config.KeyPath.Private)
                user = model.getuser(token.email)
                if password.crypt(decrypt_errorMessage, user.passwordsalt) == user.password:
                    return Response(status=204)
                newsalt = utils.CreateSalt(length=8)
                newpassword = password.crypt(decrypt_errorMessage, newsalt)
                user.password = newpassword
                user.passwordsalt = newsalt
                user.save()
                # 开始否决所有的Token
                model.token.delete().where(model.token.email == user.email).execute()
                return Response(status=204)
            else:
                raise Exceptions.InvalidToken()
        else:
            raise Exceptions.InvalidToken()
Пример #20
0
def verify():
    data = cache_verify.get(request.args.get("registerId"))
    if not data:
        raise Exceptions.InvalidToken()
    if model.getuser(data.get("email")):
        raise Exceptions.InvalidToken()
    result = model.user(username=data.get("username"),
                        email=data.get("email"),
                        password=password.crypt(data["password"]['context'],
                                                data["password"]['salt']),
                        passwordsalt=data["password"]['salt'],
                        register_time=datetime.now(),
                        last_login=0,
                        last_joinserver=0)
    result.save()
    cache_verify.delete(request.args.get("registerId"))
    return Response(status=204)
Пример #21
0
def group_signout(group_id):
    group.get_group(group_id)
    if request.is_json:
        data = request.json
        email = data['username']
        passwd = data['password']
        result = model.getuser(email)
        if not result:
            model.log_yggdrasil(operational="authserver.signout",
                                IP=request.remote_addr,
                                time=datetime.datetime.now(),
                                successful=False).save()
            raise Exceptions.InvalidCredentials()
        else:
            group.get_member(result, group_id)
            '''if result.permission == 0:
                return Response(json.dumps({
                    'error' : "ForbiddenOperationException",
                    'errorMessage' : "Invalid credentials. Invalid username or password."
                }), status=403, mimetype='application/json; charset=utf-8')'''
            if not cache_limit.get(".".join(['lock', result.email])):
                cache_limit.set(".".join(['lock', result.email]),
                                "LOCKED",
                                ttl=config.AuthLimit)
            else:
                raise Exceptions.InvalidCredentials()
            if password.crypt(passwd,
                              salt=result.passwordsalt) == result.password:
                Token_result = Token.getalltoken(result)
                if Token_result:
                    for i in Token_result:
                        if i.get("group") == group_id:
                            cache_token.delete(i)
                model.log_yggdrasil(operational="authserver.signout",
                                    user=result.uuid,
                                    IP=request.remote_addr,
                                    time=datetime.datetime.now()).save()
                return Response(status=204)
            else:
                model.log_yggdrasil(operational="authserver.signout",
                                    user=result.uuid,
                                    IP=request.remote_addr,
                                    time=datetime.datetime.now(),
                                    successful=False).save()
                raise Exceptions.InvalidCredentials()
Пример #22
0
 def post(self):
     try:
         form = self.form_loader()
     except RuntimeError:
         return
     user = getuser(email=form.email.data)
     key = self.secret_init(user)
     sent = self.send_mail(
         name = 'noreply',
         to = form.email.data,
         subject = u"[%s]重置你的密码" % self.settings['site_name'],
         content = self.render_string('mail/reset_password', key=key)
     )
     print key
     if sent:
         self.render(template_name = "mailed.html")
     else:
         # When the process of sending the mail, occur some error.
         # Whill be recode to log file.
         self.render(template_name = "mailnotsent.html")
Пример #23
0
	def getcurrentuser(self):
		self.login_required()
		u = model.getuser(session.username)
		if not u:
			raise web.seeother(r'/')
		return u[0]
Пример #24
0
 def validate_email(self, field):
     if getuser(email=field.data):
         raise ValidationError(
             u'Email已存在,是否<a href="/signin/">登录</a>?')
Пример #25
0
 def validate_password(self, field):
     user = getuser(email=self.email.data)
     if not user: return
     password = utils.string_hash(field.data, self.email.data)
     if password != user.password:
         raise ValidationError(u'Password error.')
Пример #26
0
 def get(self, user_id):
     person = getuser(id=user_id)
     if not person:
         raise web.HTTPError(404)
     self.render(person = person)
Пример #27
0
 def validate_email(self, field):
     if not getuser(email=field.data):
         raise ValidationError(u'没有这个帐号,请检查输入')
Пример #28
0
def group_authenticate(group_id):
    group.get_group(group_id)
    IReturn = {}
    if request.is_json:
        data = request.json
        user = model.getuser(data['username'])
        if not user:
            raise Exceptions.InvalidCredentials()
        '''if user.permission == 0:
            return Response(json.dumps({
                'error' : "ForbiddenOperationException",
                'errorMessage' : "You have been banned by the administrator, please contact the administrator for help"
            }), status=403, mimetype='application/json; charset=utf-8')'''
        if not cache_limit.get(".".join(['lock', user.email])):
            cache_limit.set(".".join(['lock', user.email]),
                            "LOCKED",
                            ttl=config.AuthLimit)
        else:
            raise Exceptions.InvalidCredentials()
        group.get_member(group_id, user.uuid)
        SelectedProfile = {}
        AvailableProfiles = []
        if password.crypt(data['password'],
                          user.passwordsalt) == user.password:
            # 登录成功.
            ClientToken = data.get("clientToken",
                                   str(uuid.uuid4()).replace("-", ""))
            AccessToken = str(uuid.uuid4()).replace("-", "")
            notDoubleProfile = False

            try:
                AvailableProfiles = [
                    model.format_profile(i, unsigned=True)
                    for i in model.profile.select().where(
                        model.profile.createby == user.uuid)
                ]
            except model.profile.DoesNotExist:
                pass

            Profileresult = model.getprofile_createby(user.uuid)
            if len(Profileresult) == 1:
                notDoubleProfile = True
                SelectedProfile = model.format_profile(Profileresult.get())

            cache_token.set(
                AccessToken, {
                    "clientToken": ClientToken,
                    "bind":
                    Profileresult.get().uuid if notDoubleProfile else None,
                    "user": user.uuid,
                    "group": group_id,
                    "createTime": int(time.time())
                },
                ttl=config.TokenTime.RefrushTime * config.TokenTime.TimeRange)

            IReturn = {
                "accessToken": AccessToken,
                "clientToken": ClientToken,
                "availableProfiles": AvailableProfiles,
                "selectedProfile": SelectedProfile
            }
            if "requestUser" in data:
                if data['requestUser']:
                    IReturn['user'] = model.format_user(user)

            if IReturn['selectedProfile'] == {}:
                del IReturn['selectedProfile']

            user.last_login = datetime.datetime.now()
            model.log_yggdrasil(operational="authserver.authenticate",
                                user=user.uuid,
                                otherargs=json.dumps(
                                    {"clientToken": ClientToken}),
                                IP=request.remote_addr,
                                time=datetime.datetime.now()).save()
        else:
            model.log_yggdrasil(operational="authserver.authenticate",
                                user=user.uuid,
                                IP=request.remote_addr,
                                time=datetime.datetime.now(),
                                successful=False).save()
            raise Exceptions.InvalidCredentials()
        return Response(json.dumps(IReturn),
                        mimetype='application/json; charset=utf-8')
Пример #29
0
 def get(self, uid):
     person = getuser(uid)
     self.render(person=person)
Пример #30
0
 def get(self, uid):
     person = getuser(uid)
     self.render(person=person)
Пример #31
0
def name_validate(self, field):
    if utils.special_char(field.data):
        raise ValidationError(u'昵称里面不允许有特殊字符。')
    elif getuser(name=field.data):
        raise ValidationError(u'Opps,这个昵称已经有人在用了。')
Пример #32
0
 def getcurrentuser(self):
     self.login_required()
     u = model.getuser(session.username)
     if not u:
         raise web.seeother(r'/')
     return u[0]
Пример #33
0
 def validate_email(self, field):
     user = getuser(email = field.data)
     if not user:
         raise ValidationError(u'Email 没有找到。')