Generates a unique confirmation token for the specified user.

    :param user: The user to work with
168991
def generate_confirmation_token(user):
    
    data = [str(user.id), hash_data(user.email)]
    return _security.confirm_serializer.dumps(data)
84314
def authenticate_user(self, request, user):
        
        return user.check_password(request.data.get('password')) or \
               self.check_user_token(request, user)
1288572
def verify(self, user, identity):
        
        return UserIdentityRequest(self).put(self.endpoint.verify, user, identity)
452666
def finish_user(self, subid):
    ''''''        

    p = self.revoke_token(subid)
    p.token = "finished"
    self.session.commit()
    return p
1369673
def create_user(username, password=None, email=None, first_name="", last_name="",
                role="MEMBER", login_method=None):
    

    if not login_method:
        login_method = "email" if "@" in username else "username"

    def cb():
        return _user(models.AuthUser.new(username=username,
                                         password=password,
                                         email=email,
                                         first_name=first_name,
                                         last_name=last_name,
                                         login_method=login_method,
                                         role=role))

    return signals.create_user(cb)
540075
def get_or_create_user(self, access_token, id_token, payload):
        """"""

        user_info = self.get_userinfo(access_token, id_token, payload)

        email = user_info.get('email')

        claims_verified = self.verify_claims(user_info)
        if not claims_verified:
            msg = 'Claims verification failed'
            raise SuspiciousOperation(msg)

        # email based filtering
        users = self.filter_users_by_claims(user_info)

        if len(users) == 1:
            return self.update_user(users[0], user_info)
        elif len(users) > 1:
            # In the rare case that two user accounts have the same email address,
            # bail. Randomly selecting one seems really wrong.
            msg = 'Multiple users returned'
            raise SuspiciousOperation(msg)
        elif self.get_settings('OIDC_CREATE_USER', True):
            user = self.create_user(user_info)
            return user
        else:
            LOGGER.debug('Login failed: No user with email %s found, and '
                         'OIDC_CREATE_USER is False', email)
            return None
933163
def generate_token(self, username):
        
        serializer = self.get_signature()
        return serializer.dumps(
            {
                'username': username,
                'hashhash': self.get_hashhash(username)
            }
        ).decode('UTF-8')
317765
def create
      logger.debug("Create new user")
      @user = User.new(user_params)
      if @user.save

        # Save succeeded. Render the response based on the created user.
        render json: @user,
               except: [:verification_token, :reset_token, :password_digest],
               status: 201

        # Then, issue the verification token and send the email for
        # verification.
        @user.issue_token(:verification_token)
        @user.save
        user_mailer.email_verification(@user).deliver_later
      else
        render_errors 400, @user.errors.full_messages
      end
    end
382895
public static Token<EsTokenIdentifier> obtainToken(RestClient client, User user) {
        EsToken esToken = obtainEsToken(client, user);
        return EsTokenIdentifier.createTokenFrom(esToken);
    }
209832
def topoff_user(cls, user, amount):
        
        stat, _ = cls.objects.get_or_create(user=user)
        remaining = stat.invites_remaining()
        if remaining != -1 and remaining < amount:
            stat.invites_allocated += (amount - remaining)
            stat.save()
213550
def validate_user(user,
                  device,
                  token):
    '''
    
    '''
    res = {
            'message': 'User key is invalid',
            'result': False
           }

    parameters = dict()
    parameters['user'] = user
    parameters['token'] = token
    if device:
        parameters['device'] = device

    response = query(function='validate_user',
                     method='POST',
                     header_dict={'Content-Type': 'application/x-www-form-urlencoded'},
                     data=_urlencode(parameters))

    if response['res']:
        if 'message' in response:
            _message = response.get('message', '')
            if 'status' in _message:
                if _message.get('dict', {}).get('status', None) == 1:
                    res['result'] = True
                    res['message'] = 'User key is valid.'
                else:
                    res['result'] = False
                    res['message'] = ''.join(_message.get('dict', {}).get('errors'))
    return res
235208
def get_user_flagger():
    
    user_klass = get_user_model()
    try:
        user = user_klass.objects.get(pk=COMMENT_FLAG_USER_ID)
    except user_klass.DoesNotExist:
        try:
            user = user_klass.objects.get(
                **{user_klass.USERNAME_FIELD: FLAGGER_USERNAME})
        except user_klass.DoesNotExist:
            user = user_klass.objects.create_user(FLAGGER_USERNAME)
    return user
180277
def confirm
      token = params[:token].to_s

      user = User.find_by(confirmation_token: token)

      if user.present? && user.confirmation_token_valid?
        if user.mark_as_confirmed!
          render json: {status: 'Account confirmed successfully.'}
        else
          render json: user.errors, status: 422
        end
      else
        render json: ['Invalid token'], status: :not_found
      end
    end
519283
def confirm_email_view(self, token):
        
        # Verify token
        data_items = self.token_manager.verify_token(
            token,
            self.USER_CONFIRM_EMAIL_EXPIRATION)

        # Retrieve user, user_email by ID
        user = None
        user_email = None
        if data_items:
            user, user_email = self.db_manager.get_user_and_user_email_by_id(data_items[0])

        if not user or not user_email:
            flash(_('Invalid confirmation token.'), 'error')
            return redirect(url_for('user.login'))

        # Set UserEmail.email_confirmed_at
        user_email.email_confirmed_at=datetime.utcnow()
        self.db_manager.save_user_and_user_email(user, user_email)
        self.db_manager.commit()

        # Send confirmed_email signal
        signals.user_confirmed_email.send(current_app._get_current_object(), user=user)

        # Flash a system message
        flash(_('Your email has been confirmed.'), 'success')

        # Auto-login after confirm or redirect to login page
        safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CONFIRM_ENDPOINT)
        if self.USER_AUTO_LOGIN_AFTER_CONFIRM:
            return self._do_login_user(user, safe_next_url)  # auto-login
        else:
            return redirect(url_for('user.login') + '?next=' + quote(safe_next_url))
1007401
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None):
    """"""
    assert user_id, "No user_id passed to generate_token()"
    assert isinstance(data, dict), "generate_token(data=) should be a dictionary"
    assert get_config().jwt_secret, "No JWT secret configured in pymacaron"

    if not issuer:
        issuer = get_config().jwt_issuer

    assert issuer, "No JWT issuer configured for pymacaron"

    if expire_in is None:
        expire_in = get_config().jwt_token_timeout

    if iat:
        epoch_now = iat
    else:
        epoch_now = to_epoch(timenow())
    epoch_end = epoch_now + expire_in

    data['iss'] = issuer
    data['sub'] = user_id
    data['aud'] = get_config().jwt_audience
    data['exp'] = epoch_end
    data['iat'] = epoch_now

    headers = {
        "typ": "JWT",
        "alg": "HS256",
        "iss": issuer,
    }

    log.debug("Encoding token with data %s and headers %s (secret:%s****)" % (data, headers, get_config().jwt_secret[0:8]))

    t = jwt.encode(
        data,
        get_config().jwt_secret,
        headers=headers,
    )

    if type(t) is bytes:
        t = t.decode("utf-8")

    return t
889127
def confirm_email(token):
    """"""

    expired, invalid, user = confirm_email_token_status(token)

    if not user or invalid:
        invalid = True
        do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))

    already_confirmed = user is not None and user.confirmed_at is not None

    if expired and not already_confirmed:
        send_confirmation_instructions(user)
        do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email,
                              within=_security.confirm_email_within))
    if invalid or (expired and not already_confirmed):
        return redirect(get_url(_security.confirm_error_view) or
                        url_for('send_confirmation'))

    if user != current_user:
        logout_user()

    if confirm_user(user):
        after_this_request(_commit)
        msg = 'EMAIL_CONFIRMED'
    else:
        msg = 'ALREADY_CONFIRMED'

    do_flash(*get_message(msg))

    return redirect(get_url(_security.post_confirm_view) or
                    get_url(_security.login_url))
920200
def generate_username(self, user_class):
        
        m = getattr(user_class, 'generate_username', None)
        if m:
            return m()
        else:
            max_length = user_class._meta.get_field(
                self.username_field).max_length
            return uuid.uuid4().hex[:max_length]