# 用户登录

# 概要


实现用户登录功能


# 编辑error.go文件


```bash
$  vi book/user/api/internal/logic/error.go
```


增加一些错误类型


```yaml
errorUsernameUnRegister = shared.NewDefaultError("用户未注册")
errorIncorrectPassword  = shared.NewDefaultError("用户密码错误")
```


# 填充登录逻辑代码


```bash
$ vi book/user/api/internal/logic/loginlogic.go
```


增加登录逻辑


向Login方法中填充注册逻辑


```golang
// 忽略逻辑校验
userInfo, err := l.svcCtx.UserModel.FindOneByName(req.Username)
switch err {
case nil:
	if userInfo.Password != req.Password {
		return nil, errorIncorrectPassword
	}
	return &types.UserReply{
		Id:       userInfo.Id,
		Username: userInfo.Name,
		Mobile:   userInfo.Mobile,
		Nickname: userInfo.Nickname,
		Gender:   userInfo.Gender,
	}, nil
case model.ErrNotFound:
	return nil, errorUsernameUnRegister
default:
	return nil, err
}
```


> TODO: jwt token生成见[jwt生成](https://www.yuque.com/tal-tech/go-zero/xx08s9)



# 访问登录协议


```bash
$ curl -i -X POST \
  http://127.0.0.1:8888/user/login \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
	"username":"admin",
	"password":"666666"
}'
```


> 注意：windows系统curl json需要对json进行转义。

得到响应码为`200`则代表登录成功，并且返回了用户信息


![curl-login.png](https://cdn.nlark.com/yuque/0/2020/png/465993/1603555440007-7a969230-cc8f-47d6-9cd0-d033c87acdc1.png#align=left&display=inline&height=688&margin=%5Bobject%20Object%5D&name=curl-login.png&originHeight=688&originWidth=2224&size=143975&status=done&style=none&width=2224)


<Vssue title="用户登陆" />

