Пример #1
0
    def save(self):
        email = self.cleaned_data["email"]
        first_name = self.cleaned_data["first_name"]
        last_name = self.cleaned_data["last_name"]
        password = self.cleaned_data["password"]
        password_c = self.cleaned_data["password_c"]
        bio = self.cleaned_data["bio"]
        random_username = hashlib.sha224(email).hexdigest()[:30]
        activation_code = hashlib.sha224(email).hexdigest()[:50]
        
        user = User()
        user.username = random_username
        user.email = email
        user.first_name = first_name
        user.last_name = last_name
        user.is_active = False
        user.set_password(password)
        user.save()

        user_profile = UserProfile()
        user_profile.bio = bio
        user_profile.user = user
        user_profile.activation_code = activation_code
        user_profile.save()
        send_user_activation_mail.delay(activation_code, email)
Пример #2
0
    def save(self):
        email = self.cleaned_data["email"]
        first_name = self.cleaned_data["first_name"]
        last_name = self.cleaned_data["last_name"]
        password = self.cleaned_data["password"]
        password_c = self.cleaned_data["password_c"]
        bio = self.cleaned_data["bio"]
        random_username = hashlib.sha224(email).hexdigest()[:30]
        activation_code = hashlib.sha224(email).hexdigest()[:50]

        user = User()
        user.username = random_username
        user.email = email
        user.first_name = first_name
        user.last_name = last_name
        user.is_active = False
        user.set_password(password)
        user.save()

        user_profile = UserProfile()
        user_profile.bio = bio
        user_profile.user = user
        user_profile.activation_code = activation_code
        user_profile.save()
        send_user_activation_mail.delay(activation_code, email)
Пример #3
0
    def create(self, validated_data):
        username = validated_data.get('username')
        email = validated_data.get('email')
        password = validated_data.get('password')

        user = User.objects.create_user(username, email, password)
        user_profile = UserProfile()
        user_profile.user = user
        user_profile.save(using='write')
        return user
Пример #4
0
def login_evernote_token(request):
    """ as get_evernote_token(), but logs the user in as well
    """
    everAuth = EvernoteAPI()
    credentials = everAuth.get_user_token(request)
    if not credentials:
        return HttpResponseRedirect(
            reverse('account.views.login_page', args=[]))
    if request.user.is_authenticated():
        user = request.user
    else:
        evernoteHost = settings.EVERNOTE_HOST
        userStoreUri = "https://" + evernoteHost + "/edam/user"
        userStoreHttpClient = THttpClient.THttpClient(userStoreUri)
        userStoreProtocol = TBinaryProtocol.TBinaryProtocol(
            userStoreHttpClient)
        userStore = UserStore.Client(userStoreProtocol)
        evernoteUser = userStore.getUser(credentials['oauth_token'])
        user = authenticate(username=evernoteUser.username,
                            password=str(evernoteUser.id))
        if not user:
            newUser = User.objects.create_user(evernoteUser.username,
                                               evernoteUser.email,
                                               str(evernoteUser.id))
            names = evernoteUser.name.split() if evernoteUser.name else None
            newUser.first_name = names[0] if names and len(names) > 0 else ""
            newUser.last_name = names[1] if names and len(names) > 1 else ""
            newUser.save()
            user = authenticate(username=evernoteUser.username,
                                password=str(evernoteUser.id))
        login(request, user)

    try:
        expires_time = datetime.fromtimestamp(int(credentials['expires']))
    except TypeError:
        logging.error("Error parsing token expires time")
        expires_time = datetime.now()

    profile = UserProfile()
    profile.user = user
    profile.evernote_token = credentials['oauth_token']
    profile.evernote_token_expires_time = expires_time
    profile.evernote_note_store_url = credentials['edam_noteStoreUrl']
    profile.save()
    return HttpResponseRedirect(reverse('base.views.index', args=[]))
Пример #5
0
def login_core(request, username, password):
    ret = False
    
    if username == 'admin':
        # 特殊用户 admin
        user = authenticate(username=username, password=password)
    else:
        if password == '':
            return False
        # LDAP验证
        if not login_ldap(username, password):
            return False
            
        # 检查此用户是否存在,如果不存在,则自动插入用户记录
        res = User.objects.filter(username=username)
        if not res:
            # 从LDAP获取用户信息
            dd = search_user(username)[0]
            password = make_password(username, salt=None, hasher='default')
            user = User(username=username, password=password, email=dd['mail'])
            user.save()
            # 用户附加信息
            profile = UserProfile()
            profile.department = dd['department']
            profile.phone = dd['phone']
            profile.realname = dd['cn']
            profile.user = user
            profile.save()
        
        # 这里请注意   *** password=username ***
        user = authenticate(username=username, password=username)
            
    # 登陆核心方法
    if user:
        if user.is_active:
            auth_login(request, user)
            ret = True
        else:
            messages.add_message(request, messages.INFO, _(u'用户没有激活'))
    else:
        messages.add_message(request, messages.INFO, _(u'用户不存在'))
    return ret
Пример #6
0
def login_evernote_token(request):
    """ as get_evernote_token(), but logs the user in as well
    """
    everAuth = EvernoteAPI()
    credentials = everAuth.get_user_token(request)
    if not credentials:
        return HttpResponseRedirect(reverse('account.views.login_page', args=[]))
    if request.user.is_authenticated():
        user = request.user
    else:
        evernoteHost = settings.EVERNOTE_HOST
        userStoreUri = "https://" + evernoteHost + "/edam/user"
        userStoreHttpClient = THttpClient.THttpClient(userStoreUri)
        userStoreProtocol = TBinaryProtocol.TBinaryProtocol(userStoreHttpClient)
        userStore = UserStore.Client(userStoreProtocol)
        evernoteUser = userStore.getUser(credentials['oauth_token'])
        user = authenticate(username=evernoteUser.username, password=str(evernoteUser.id))
        if not user:
            newUser = User.objects.create_user(evernoteUser.username, evernoteUser.email, str(evernoteUser.id))
            names = evernoteUser.name.split() if evernoteUser.name else None
            newUser.first_name = names[0] if names and len(names) > 0 else ""
            newUser.last_name = names[1] if names and len(names) > 1 else ""
            newUser.save()
            user = authenticate(username=evernoteUser.username, password=str(evernoteUser.id))
        login(request, user)

    try:
        expires_time = datetime.fromtimestamp(int(credentials['expires']))
    except TypeError:
        logging.error("Error parsing token expires time")
        expires_time = datetime.now()

    profile = UserProfile()
    profile.user = user
    profile.evernote_token = credentials['oauth_token']
    profile.evernote_token_expires_time = expires_time
    profile.evernote_note_store_url = credentials['edam_noteStoreUrl']
    profile.save()
    return HttpResponseRedirect(reverse('base.views.index', args=[]))
Пример #7
0
    def post(self, request, format=None):
        resutl = {}
        serializer = UserRegisterSerializer(data=request.data)
        if serializer.is_valid():
            username = serializer.validated_data.get('username')
            password = serializer.validated_data.get('password')
            email = serializer.validated_data.get('email')
            type = serializer.validated_data.get('type', 0)
            auth_user = User()
            auth_user.username = username
            auth_user.set_password(password)
            auth_user.email = email
            auth_user.save()

            # 保存user扩展
            userProfile = UserProfile()
            userProfile.user = auth_user
            userProfile.telephone = username
            userProfile.type = type
            userProfile.save()

            return Response({'status': 'ok'})
Пример #8
0
def register(request):
    '''
    Register a new user
    '''
    template = 'account/register.html'
    if request.method == 'GET':
        return render(request, template, {
            'userForm': UserForm(),
        })
    # POST
    userForm = UserForm(request.POST)
    if not userForm.is_valid():
        return render(request, template, {
            'userForm': userForm,
        })
    user = userForm.save()
    userProfile = UserProfile()
    userProfile.user = user
    userProfile.name = 'User還未命名'
    userProfile.lavel = 0
    userProfile.save()
    messages.success(request, '歡迎註冊')
    return redirect('account:login')
Пример #9
0
    def get_blog_user(self):
        oauth_access_token = self.access_token['access_token']
        oauth_expires = int(self.access_token['expires_in'])

        oauth_logins = OauthLogin.objects.using('read').filter(
            auth_type=OauthLogin.TYPE.QQ,
            oauth_access_token=oauth_access_token)
        if oauth_logins.exists():
            oauth_login = oauth_logins[0]
            user_id = oauth_login.user_id
            user = User.objects.using('read').get(id=user_id)
        else:
            uid = self.get_openid()
            oauth_logins = OauthLogin.objects.using('read').filter(
                auth_type=OauthLogin.TYPE.QQ, oauth_id=uid)
            if oauth_logins.exists():
                oauth_login = oauth_logins[0]
                user_id = oauth_login.user_id
                user = User.objects.using('read').get(id=user_id)
            else:
                user_info = self.get_qq_info()
                nick_name = user_info[
                    'nickname'] if 'nickname' in user_info else 'QQ用户{random_str}'.format(
                        random_str=generate_verification_code(3))
                if 'gender' in user_info:
                    gender = UserProfile.GENDER.MALE if user_info[
                        'gender'] == '男' else UserProfile.GENDER.FEMALE
                else:
                    gender = UserProfile.GENDER.MALE

                avatar_img = None
                if 'figureurl_qq_2' in user_info:
                    avatar = user_info['figureurl_qq_2']
                elif 'figureurl_qq_1' in user_info:
                    avatar = user_info['figureurl_qq_1']
                else:
                    avatar = None
                if avatar:
                    req = requests.get(avatar)
                    file_content = ContentFile(req.content)
                    avatar_img = get_thumbnail(file_content, 100, 100)

                result_name = nick_name
                all_user = User.objects.using('read').all()
                email_users = all_user.filter(username=nick_name)
                if email_users.exists():
                    rand_str = generate_verification_code()
                    result_name = nick_name + rand_str
                    while True:
                        if not all_user.filter(username=result_name).exists():
                            break
                        rand_str = generate_verification_code()
                        result_name = nick_name + rand_str

                user = User()
                user.username = result_name
                user.set_password('888888')
                user.save(using='write')
                user_profile = UserProfile()
                user_profile.user = user
                user_profile.gender = gender
                if avatar_img is not None:
                    user_profile.avatar = avatar_img
                user_profile.save(using='write')

                oauth_login = OauthLogin()
                oauth_login.auth_type = OauthLogin.TYPE.QQ
                oauth_login.oauth_id = uid
                oauth_login.user_id = user.id

        # update access token
        oauth_login.oauth_access_token = oauth_access_token
        oauth_login.oauth_expires = oauth_expires
        oauth_login.save(using='write')
        return user
Пример #10
0
    def get_redirect_url(self, *args, **kwargs):
        # Step 1. Use the request token in the session to build a new client.
        consumer = oauth.Consumer(settings.OAUTH_CONSUMER_KEY,
                                  settings.OAUTH_CONSUMER_SECRET)
        token = oauth.Token(
            self.request.session['request_token']['oauth_token'],
            self.request.session['request_token']['oauth_token_secret'])
        client = oauth.Client(consumer, token)
        client.set_signature_method(SignatureMethod_RSA_SHA1())

        # Step 2. Request the authorized access token from Jira.
        try:
            resp, content = client.request(settings.OAUTH_ACCESS_TOKEN_URL,
                                           "POST")
        except Exception:
            messages.add_message(
                self.request, messages.ERROR,
                'Error: Connection to Jira failed. Please contact an Administrator'
            )
            return '/'
        if resp['status'] != '200':
            messages.add_message(
                self.request, messages.ERROR,
                'Error: Connection to Jira failed. Please contact an Administrator'
            )
            return '/'

        access_token = dict(urllib.parse.parse_qsl(content.decode()))

        module_dir = os.path.dirname(__file__)  # get current directory
        with open(module_dir + '/rsa.pem', 'r') as f:
            key_cert = f.read()

        oauth_dict = {
            'access_token': access_token['oauth_token'],
            'access_token_secret': access_token['oauth_token_secret'],
            'consumer_key': settings.OAUTH_CONSUMER_KEY,
            'key_cert': key_cert
        }

        jira = JIRA(server=settings.JIRA_URL, oauth=oauth_dict)
        username = jira.current_user()
        email = jira.user(username).emailAddress
        url = '/'
        # Step 3. Lookup the user or create them if they don't exist.
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # Save our permanent token and secret for later.
            user = User.objects.create_user(
                username=username, password=access_token['oauth_token_secret'])
            profile = UserProfile()
            profile.user = user
            profile.save()
            user.userprofile.email_addr = email
            url = reverse('account:settings')
        user.userprofile.oauth_token = access_token['oauth_token']
        user.userprofile.oauth_secret = access_token['oauth_token_secret']
        user.userprofile.save()
        user.set_password(access_token['oauth_token_secret'])
        user.save()
        user = authenticate(username=username,
                            password=access_token['oauth_token_secret'])
        login(self.request, user)
        # redirect user to settings page to complete profile
        return url
Пример #11
0
    def get_blog_user(self):
        access_token = self.access_token
        oauth_access_token = access_token['access_token']
        oauth_expires = access_token['expires_in']
        uid = access_token['uid']

        oauth_logins = OauthLogin.objects.using('read').filter(auth_type=OauthLogin.TYPE.WEIBO,
                                                               oauth_access_token=oauth_access_token)
        if oauth_logins.exists():
            oauth_login = oauth_logins[0]
            user_id = oauth_login.user_id
            user = User.objects.using('read').get(id=user_id)
        else:
            oauth_logins = OauthLogin.objects.using('read').filter(auth_type=OauthLogin.TYPE.WEIBO,
                                                                   oauth_id=uid)
            if oauth_logins.exists():
                oauth_login = oauth_logins[0]
                user_id = oauth_login.user_id
                user = User.objects.using('read').get(id=user_id)
            else:
                user_info = self.get_weibo_info()
                nick_name = user_info['screen_name'] if 'screen_name' in user_info else '微博用户{random_str}'.format(
                    random_str=generate_verification_code(3))
                gender = user_info['gender'] if 'gender' in user_info else UserProfile.GENDER.MALE

                avatar_img = None
                if 'avatar_large' in user_info:
                    avatar = user_info['avatar_large']
                elif 'profile_image_url' in user_info:
                    avatar = user_info['profile_image_url']
                else:
                    avatar = None
                if avatar:
                    req = requests.get(avatar)
                    file_content = ContentFile(req.content)
                    avatar_img = get_thumbnail(file_content, 100, 100)

                result_name = nick_name
                all_user = User.objects.using('read').all()
                email_users = all_user.filter(username=nick_name)
                if email_users.exists():
                    rand_str = generate_verification_code()
                    result_name = nick_name + rand_str
                    while True:
                        if not all_user.filter(username=result_name).exists():
                            break
                        rand_str = generate_verification_code()
                        result_name = nick_name + rand_str

                user = User()
                user.username = result_name
                user.set_password('888888')
                user.save(using='write')
                user_profile = UserProfile()
                user_profile.user = user
                user_profile.gender = gender
                if avatar_img is not None:
                    user_profile.avatar = avatar_img
                user_profile.save(using='write')

                oauth_login = OauthLogin()
                oauth_login.auth_type = OauthLogin.TYPE.WEIBO
                oauth_login.oauth_id = uid
                oauth_login.user_id = user.id

        # update access token
        oauth_login.oauth_access_token = oauth_access_token
        oauth_login.oauth_expires = oauth_expires
        oauth_login.save(using='write')
        return user