# FaS Element

**Web component for easy passkey authentication integration** - Based on FaS Platform

FaS Element is a custom web component that provides a beautiful, Material-UI inspired UI for passkey authentication. Built specifically for the FaS Platform, it integrates seamlessly with your existing React applications and backend APIs.

## 🚀 Quick Start

### 1. Install

```bash
npm install @passkey-fas/element
```

### 2. Use in HTML (Proxy Mode - Recommended)

```html
<!DOCTYPE html>
<html>
<head>
    <title>My App</title>
</head>
<body>
    <!-- Just add the element -->
    <fas-element 
        client-id="your-client-id"
        api-url="/api/webauthn"
        use-proxy="true">
    </fas-element>

    <!-- Import the script -->
    <script src="https://unpkg.com/@passkey-fas/element@1.0.0/dist/fas-element.js"></script>
</body>
</html>
```

### 3. Use with React (Recommended for FaS Platform)

```jsx
import React from 'react';
import '@passkey-fas/element';

function AuthPage() {
  const handleSuccess = (event) => {
    const { type, user, token } = event.detail;
    // Store token
    localStorage.setItem('accessToken', token);
    // Redirect to dashboard
    window.location.href = '/dashboard';
  };

  const handleError = (event) => {
    console.error('Auth error:', event.detail.message);
  };

  return (
    <div>
      <fas-element 
        client-id={process.env.REACT_APP_FAS_CLIENT_ID}
        api-url="/api/webauthn"
        use-proxy="true"
        onFas-success={handleSuccess}
        onFas-error={handleError}
      />
    </div>
  );
}

export default AuthPage;
```

## 🏗️ Backend Integration (Express.js)

FaS Element works best with your Express.js backend as a proxy:

```javascript
// server/routes/webauthn.js
const express = require('express');
const FaSSDK = require('@passkey-fas/webauthn-sdk');

const router = express.Router();
const fasSDK = new FaSSDK({
  clientId: process.env.FAS_CLIENT_ID,
  clientSecret: process.env.FAS_CLIENT_SECRET,
  apiBase: 'https://fas-l450.onrender.com/api/webauthn'
});

// Proxy registration endpoints
router.post('/register/start', async (req, res) => {
  try {
    const options = await fasSDK.registerPasskey(req.body.email, req.body.fullname);
    res.json(options);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

router.post('/register/finish', async (req, res) => {
  try {
    const result = await fasSDK.verifyPasskeyRegistration(req.body);
    res.json(result);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// Proxy authentication endpoints
router.post('/authenticate/start', async (req, res) => {
  try {
    const options = await fasSDK.authenticatePasskey(req.body.email);
    res.json(options);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

router.post('/authenticate/finish', async (req, res) => {
  try {
    const result = await fasSDK.loginWithPasskey(req.body);
    res.json(result);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

module.exports = router;
```

## 🎛️ Attributes

| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| `client-id` | string | - | **Required** Your FaS project client ID |
| `api-url` | string | `/api/webauthn` | API base URL (should point to your backend proxy) |
| `use-proxy` | boolean | `true` | Use backend proxy (recommended for security) |
| `theme` | string | `material` | Theme name (currently supports Material-UI style) |
| `lang` | string | `vi` | Language code |

## 🎪 Events

### `fas-success`

Fired when authentication is successful.

```javascript
authElement.addEventListener('fas-success', (event) => {
    const { type, user, token } = event.detail;
    // type: 'login', 'register', or 'quick-login'
    // user: { id, email, fullname, lastLogin }
    // token: JWT token string
    
    // Store token for API calls
    localStorage.setItem('accessToken', token);
    
    // Redirect to protected route
    window.location.href = '/dashboard';
});
```

### `fas-error`

Fired when an error occurs.

```javascript
authElement.addEventListener('fas-error', (event) => {
    const { message } = event.detail;
    console.error('Authentication error:', message);
    
    // Show user-friendly error
    alert(`Lỗi xác thực: ${message}`);
});
```

## 🔧 Methods

### `reset()`

Reset the element to initial login state.

```javascript
const authElement = document.querySelector('fas-element');
authElement.reset();
```

### `getAuthData()`

Get the current authentication data.

```javascript
const authData = authElement.getAuthData();
if (authData) {
    console.log('User:', authData.user);
    console.log('Token:', authData.token);
}
```

## 🎨 Styling

FaS Element uses Material-UI inspired design with CSS custom properties:

```css
fas-element {
    --primary-color: #1976d2;
    --primary-hover: #1565c0;
    --error-color: #d32f2f;
    --success-color: #2e7d32;
    --text-primary: rgba(0, 0, 0, 0.87);
    --text-secondary: rgba(0, 0, 0, 0.6);
    max-width: 400px;
}
```

## 🔒 Security

### Proxy Mode (Recommended)

```html
<fas-element 
    client-id="your-client-id"
    use-proxy="true"
    api-url="/api/webauthn">
</fas-element>
```

✅ **Secure**: Client secret stays on your backend
✅ **CORS-friendly**: No cross-origin issues
✅ **Token handling**: Your backend manages JWT tokens

### Environment Variables

```bash
# .env
REACT_APP_FAS_CLIENT_ID=your-client-id
FAS_CLIENT_SECRET=your-client-secret  # Backend only
```

## 🛠️ Integration Examples

### With Material-UI Theme

```jsx
import { ThemeProvider, createTheme } from '@mui/material/styles';
import '@passkey-fas/element';

const theme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
    },
  },
});

function App() {
  return (
    <ThemeProvider theme={theme}>
      <fas-element 
        client-id={process.env.REACT_APP_FAS_CLIENT_ID}
        style={{
          '--primary-color': theme.palette.primary.main,
          '--primary-hover': theme.palette.primary.dark,
        }}
      />
    </ThemeProvider>
  );
}
```

### With React Router

```jsx
import { useNavigate } from 'react-router-dom';

function LoginPage() {
  const navigate = useNavigate();

  const handleSuccess = (event) => {
    const { user, token } = event.detail;
    localStorage.setItem('accessToken', token);
    navigate('/dashboard');
  };

  return (
    <fas-element 
      client-id={process.env.REACT_APP_FAS_CLIENT_ID}
      onFas-success={handleSuccess}
    />
  );
}
```

## 🌏 Browser Support

- ✅ Chrome 67+
- ✅ Firefox 60+
- ✅ Safari 14+
- ✅ Edge 18+

## 📱 Features

- **🔐 Passkey Authentication** - Secure, passwordless login
- **📝 User Registration** - Create accounts with passkeys
- **⚡ Quick Login** - Login without typing email
- **🎨 Material Design** - Beautiful, responsive UI based on Material-UI
- **🔧 React Integration** - Perfect for React applications
- **🛡️ Secure Proxy Mode** - Keep secrets on your backend
- **🌍 Vietnamese Language** - Localized for Vietnamese users
- **📱 Mobile Friendly** - Works on all devices

## 🤝 Contributing

We welcome contributions! Please see our project repository for details.

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🆘 Support

- 📧 Email: support@fas-platform.com
- 🌐 Website: https://fas-l450.onrender.com
- 📚 Documentation: https://fas-l450.onrender.com/docs

---

**Made with ❤️ by the FaS Team** - Passwordless authentication for everyone! 