amis+django+token实现用户认证
时间: 2023-11-15 20:04:31 浏览: 259
要使用AMis和Django结合Token实现用户认证,您可以按照以下步骤进行操作:
1. 安装Django框架和django-rest-framework库。
2. 创建一个Django应用程序并配置好数据库。您可以使用以下命令创建一个名为'myapp'的Django应用程序。
```
django-admin startapp myapp
```
3. 在Django项目的settings.py文件中配置应用程序和REST框架。
```python
INSTALLED_APPS = [
...
'rest_framework',
'myapp',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
```
4. 创建一个用户模型并迁移数据库。
```python
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
```
5. 创建一个视图函数来处理用户登录和创建新用户。
```python
from django.contrib.auth import authenticate, login
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['POST'])
def login_view(request):
email = request.data.get('email')
password = request.data.get('password')
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
else:
return Response({'error': 'Invalid credentials'})
@api_view(['POST'])
def register_view(request):
email = request.data.get('email')
password = request.data.get('password')
user = User.objects.create_user(email=email, password=password)
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
```
6. 创建AMis页面,使用axios库发送POST请求到这些视图函数以进行用户登录和注册。
```javascript
import React, { useState } from 'react';
import axios from 'axios';
import { amis } from '@amis/core';
function LoginForm(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/api/login/', { email, password });
localStorage.setItem('token', response.data.token);
props.onSuccess();
} catch (error) {
console.error(error);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="email">Email</label>
<input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div>
<label htmlFor="password">Password</label>
<input type="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<button type="submit">Login</button>
</form>
);
}
function RegisterForm(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/api/register/', { email, password });
localStorage.setItem('token', response.data.token);
props.onSuccess();
} catch (error) {
console.error(error);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="email">Email</label>
<input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div>
<label htmlFor="password">Password</label>
<input type="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<button type="submit">Register</button>
</form>
);
}
const schema = {
type: 'page',
body: [
{
type: 'form',
title: 'Login',
mode: 'horizontal',
api: {
method: 'post',
url: '/api/login/',
data: {
email: '${email}',
password: '${password}',
},
adaptor: (payload) => ({ ...payload.data, success: true }),
},
controls: [
{
type: 'email',
name: 'email',
label: 'Email',
required: true,
},
{
type: 'password',
name: 'password',
label: 'Password',
required: true,
},
{
type: 'submit',
label: 'Login',
primary: true,
},
],
},
{
type: 'form',
title: 'Register',
mode: 'horizontal',
api: {
method: 'post',
url: '/api/register/',
data: {
email: '${email}',
password: '${password}',
},
adaptor: (payload) => ({ ...payload.data, success: true }),
},
controls: [
{
type: 'email',
name: 'email',
label: 'Email',
required: true,
},
{
type: 'password',
name: 'password',
label: 'Password',
required: true,
},
{
type: 'submit',
label: 'Register',
primary: true,
},
],
},
],
};
function App() {
const [token, setToken] = useState(localStorage.getItem('token'));
const handleSuccess = () => {
setToken(localStorage.getItem('token'));
};
const handleLogout = () => {
localStorage.removeItem('token');
setToken(null);
};
return (
<div>
{token ? (
<div>
<p>You are logged in.</p>
<button onClick={handleLogout}>Logout</button>
</div>
) : (
<div>
<LoginForm onSuccess={handleSuccess} />
<RegisterForm onSuccess={handleSuccess} />
</div>
)}
<amis schema={schema} />
</div>
);
}
export default App;
```
以上就是使用AMis和Django结合Token实现用户认证的步骤。
阅读全文