Source code for nexacon.auth

"""
Authentication Service
External authentication using nx_token only
"""

from typing import Dict, Any
from nexacon.exceptions import ValidationError, AuthenticationError


[docs] class Auth: """Authentication service for external integration using nx_token"""
[docs] def __init__(self, client): self.client = client
[docs] def generate_token(self, username: str, phone: str = None, email: str = None) -> Dict[str, Any]: """ Generate nx_token for a user. This endpoint requires API key and secret key (no nx_token needed). It will auto-register the user if they don't exist. Args: username: User identifier (phone number or email) phone: Optional phone number (defaults to username if starts with +) email: Optional email address Returns: Dictionary containing the generated nx_token Raises: ValidationError: If username is not provided APIError: If token generation fails """ if not username: raise ValidationError("Username is required") data = { "username": username } if phone: data["phone"] = phone if email: data["email"] = email response = self.client._request("POST", "/auth/generate-token/", data) if "error" in response: raise AuthenticationError(response.get("error", "Failed to generate token")) # Set the token automatically after generation if "token" in response: self.client.set_token(response["token"]) return response
[docs] def verify_token(self) -> Dict[str, Any]: """ Verify the current nx_token is valid. Returns: User information if token is valid Raises: ValidationError: If no token is set AuthenticationError: If token is invalid """ token = self.client.get_token() if not token: raise ValidationError("nx_token is required. Initialize client with nx_token parameter or call generate_token().") response = self.client._request("GET", "/auth/user/") if "error" in response: raise AuthenticationError("Invalid token") return response
[docs] def logout(self) -> Dict[str, Any]: """ Logout the current session. Returns: Logout confirmation """ return self.client._request("POST", "/auth/logout/")
[docs] def get_user(self) -> Dict[str, Any]: """ Get current user information. Returns: User information """ return self.client._request("GET", "/auth/user/")