本帖最后由 a7741200 于 2024-3-11 01:01 编辑
[PHP] 纯文本查看 复制代码 <?php
namespace app\index\controller;
use app\BaseController;
use app\index\service\LoginService;
use app\model\user\User;
use PDO;
use think\db\exception\PDOException;
use think\facade\View;
class Login extends BaseController
{
/**
* 登录
*/
public function index(LoginService $loginService)
{
if (request()->isPost()) {
$param = input('post.');
$host="127.0.0.1";
$dbname="Account";
$user="sa";
$pass="123456";
try {
$dbh = new PDO("sqlsrv:Server=$host;Database=$dbname", $user, $pass);
} catch(PDOException $e) {
echo $e->getMessage();
exit;
}
// 执行查询操作
$query = "SELECT account, password FROM user WHERE account = :phone and password = :password";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':phone', $param['phone']);
$stmt->bindParam(':password', $param['password']);
// 执行查询操作
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row){
//查询 注册
$userModel = new User();
$userInfo = $userModel->where('nickname', $param['phone'])->find();
if (empty($userInfo)) {
$regParam = [
'code' => uniqid(),
'source_id' => 3,
'nickname' => $param['phone'],
'phone' => $param['phone'],
'avatar' => '/static/home/default/image/avatar.jpeg',
'password' => makePassword($param['password']),
'register_time' => now(),
'create_time' => now()
];
$res = $userModel->insertOne($regParam);
if ($res['code'] == 0) {
$userInfo = $userModel->where('nickname', $param['phone'])->find();
}
}
session('home_user_id', $userInfo['id']);
session('home_user_name', $userInfo['nickname']);
session('home_user_avatar', $userInfo['avatar']);
return json(dataReturn(0, "登陆成功"));
}else{
return json(dataReturn(-1, "登录失败"));
}
// 清理资源
unset($stmt);
unset($dbh);
unset($dbh); unset($stmt);
}
return View::fetch();
}
/**
* 注册
*/
public function reg(LoginService $loginService)
{
if (request()->isPost()) {
return json($loginService->doReg(input('post.')));
}
return View::fetch();
}
/**
* 退出登录
*/
public function loginOut()
{
session('home_user_id', null);
session('home_user_name', null);
session('home_user_avatar', null);
return redirect('/index/cate');
}
/**
* 验证码
*/
public function captcha()
{
View::assign([
'phone' => input('param.phone'),
'type' => input('param.type')
]);
return View::fetch();
}
/**
* 忘记密码
*/
public function forget(LoginService $loginService)
{
if (request()->isPost()) {
return json($loginService->forgetPassword(input('post.')));
}
return View::fetch();
}
}
以上代码中的账号登录是连接mssql 。那么我想把密码进行加密后的结果与数据库中password字段中的结果进行对比,如果一样就登录成功。
因为写入数据库的密码是经过加密的。所以使用登录功能就需要验证用户输入的密码也经过相同方式加密后是否与数据库中一样。
密码加密方式是C#(PasswordHash.cs)
|