Example #1
0
    def ensure_user(self,
                    username,
                    is_active=True,
                    first_name=None,
                    last_name=None,
                    email=None,
                    **kwargs):
        from noc.aaa.models.user import User

        changed = False
        try:
            u = User.objects.get(username=username)
        except User.DoesNotExist:
            self.logger.info("Creating local user %s", username)
            u = User(username=username, is_active=is_active)
            u.set_unusable_password()
            changed = True
        for k, v in [
            ("is_active", is_active),
            ("first_name", first_name),
            ("last_name", last_name),
            ("email", email),
        ]:
            cv = getattr(u, k)
            if cv != v and v is not None:
                self.logger.info("Changing user %s %s: %s -> %s", username, k,
                                 cv, v)
                setattr(u, k, v)
                changed = True
        # Check changes
        if changed:
            u.save()
        return u
Example #2
0
 def handle_add(self, *args, **options):
     if "username" not in options:
         raise CommandError("Username is not set")
     if "email" not in options:
         raise CommandError("Email is not set")
     if "pwgen" in options:
         passwd = "".join(
             random.choice(self.pwset) for _ in range(self.PWLEN))
     else:
         passwd = None
     if not passwd:
         raise CommandError("Password is not set")
     permissions = set()
     if not options.get("template"):
         raise CommandError("template permission not set")
     for t in options["template"]:
         if t not in self.TEMPLATES:
             raise CommandError("Invalid template '%s'" % t)
         permissions.update(self.TEMPLATES[t])
     if not permissions:
         raise CommandError("No permissions set")
     # Create user
     u = User(username=options["username"],
              email=options["email"],
              is_active=True)
     u.set_password(passwd)
     u.save()
     for p in permissions:
         try:
             perm = Permission.objects.get(name=p)
         except Permission.DoesNotExist:
             perm = Permission(name=p)
             perm.save()
         perm.users.add(u)
     print(passwd)
Example #3
0
def get_current_user(remote_user: Optional[str] = Header(None, alias="Remote-User")) -> User:
    """
    Get request current user

    :param remote_user:
    :return:
    """
    if not remote_user:
        raise HTTPException(403, "Not authorized")
    user = User.get_by_username(remote_user)
    if not user:
        raise HTTPException(403, "Not authorized")
    if not user.is_active:
        raise HTTPException(403, "Not authorized")
    return user
Example #4
0
def get_user_scope(
    scopes: SecurityScopes, remote_user: Optional[str] = Header(None, alias="Remote-User")
) -> User:
    """
    Get request current user, when having scope access

    :param scopes:
    :param remote_user:
    :return:
    """
    if not remote_user:
        raise HTTPException(403, "Not authorized")
    user = User.get_by_username(remote_user)
    if not user:
        raise HTTPException(403, "Not authorized")
    if not user.is_active:
        raise HTTPException(403, "Not authorized")
    # @todo: Check user's active scopes against {scopes.scopes}
    return user
Example #5
0
 def authenticate(self, handler, credentials):
     """
     Authenticate user. Returns True when user is authenticated
     """
     c = credentials.copy()
     for f in self.HIDDEN_FIELDS:
         if f in c:
             c[f] = "***"
     le = "No active auth methods"
     for method in self.iter_methods():
         bc = BaseAuthBackend.get_backend(method)
         if not bc:
             self.logger.error("Cannot initialize backend '%s'", method)
             continue
         backend = bc(self)
         self.logger.info("Authenticating credentials %s using method %s",
                          c, method)
         try:
             user = backend.authenticate(**credentials)
             metrics["auth_try", ("method", method)] += 1
         except backend.LoginError as e:
             self.logger.info("[%s] Login Error: %s", method, smart_text(e))
             metrics["auth_fail", ("method", method)] += 1
             le = smart_text(e)
             continue
         self.logger.info("Authorized credentials %s as user %s", c, user)
         metrics["auth_success", ("method", method)] += 1
         # Set cookie
         handler.set_secure_cookie("noc_user",
                                   user,
                                   expires_days=config.login.session_ttl,
                                   httponly=True,
                                   secure=True)
         # Register last login
         if config.login.register_last_login:
             u = User.get_by_username(user)
             if u:
                 u.register_login()
         return True
     self.logger.error("Login failed for %s: %s", c, le)
     return False
Example #6
0
 def getter():
     u = User.get_by_username(user)
     if not u:
         metrics["error", ("type", "user_not_found")] += 1
     return u