ruoyi v3.2整合gitee登录

login.vue

 <el-button @click="mayun()">码云登陆</el-button>
 mayun() {
      loginMayun().then(res => {
        Cookies.set("user-uuid", res.uuid)
        console.log(res)
        location.href = res.authorize
      })


    },

创建 callback.vue


<template>
  <div v-loading="loading" style="height: 100%;width: 100%;">
    正在加载中...
  </div>

</template>

<script>
import Cookies from "js-cookie";


export default {
  name: "loginByGitee",
  data() {
    return {
      loading: true
    }
  },
  mounted() {
    this.loading = true;
    console.log("uuid", Cookies.get("user-uuid"))
    const formBody = {
      uuid: Cookies.get("user-uuid"),
      code: this.$route.query.code
    }
    // debugger
    this.$store.dispatch("LoginByGitee", formBody).then(() => {
      this.$router.push({path: this.redirect || "/"}).catch(() => {
      });
    }).catch(() => {
      this.loading = false;
    });
  }
}
</script>

<style scoped>

</style>

注意放行路径---- /callback,在permission.js

const whiteList = ['/login', '/auth-redirect', '/bind', '/register','/callback']

添加路由

 {
    path: '/callback',
    component: (resolve) => require(['@/views/callback'], resolve),
    hidden: true
  },

在user.js加入代码


    // Gitee登录
    LoginByGitee({commit}, body) {
      return new Promise((resolve, reject) => {
        loginByGitee(body.code, body.uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
          location.href="/login"
        })
      })
    },

在login.js加入



//码云登陆
export function loginMayun() {
  return request({
    url: '/mayunLogin',
    method: 'get',
    headers: {
      isToken: false
    }
  })
}
export function loginByGitee(code, uuid) {
  const data = {
    code,
    source: "Gitee",
    uuid
  }
  return request({
    url: '/loginByGitee',
    headers: {
      isToken: false
    },
    method: 'post',
    data: data
  })
}

前端整合完成
后端整合

 /**
     * 码云登录
     *
     *
     * @return {@code AjaxResult}
     * @throws Exception 
     */
    @GetMapping("/mayunLogin")
    public AjaxResult mayunLogin() throws Exception {


        AjaxResult result = new AjaxResult();
        AuthRequest authRequest = getAuthRequest();
        String uuid = IdUtils.fastUUID();
        String authorize = authRequest.authorize(uuid);
        result.put("uuid", uuid);
        result.put("authorize", authorize);
        System.out.println("authorize = " + authorize);
        System.out.println("uuid = " + uuid);
        return result;

    }

    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId("")
                .clientSecret("")
                .redirectUri("http://localhost:80/callback")
                .build());
    }
    

    @PostMapping("/loginByGitee")
    public AjaxResult loginByGitee(@RequestBody LoginByOtherSourceBody loginByOtherSourceBody) {
        if (StringUtils.isBlank(loginByOtherSourceBody.getSource())) {
            loginByOtherSourceBody.setSource("gitee");
        }
        AjaxResult ajax = AjaxResult.success();
        String token = loginService
                .loginByOtherSource(loginByOtherSourceBody.getCode(), loginByOtherSourceBody.getSource(), loginByOtherSourceBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

SysLoginService.java



    public String loginByOtherSource(String code, String source, String uuid) {
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId("")
                .clientSecret("")
                .redirectUri("http://localhost:80/callback")
                .build());
        AuthResponse<AuthUser> login = authRequest.login(AuthCallback.builder().state(uuid).code(code).build());
        if (login.getCode() != 2000) {
            throw new CustomException("登录失败");
        }
        String nickname = login.getData().getNickname();
        String username = login.getData().getUsername();
        String avatar = login.getData().getAvatar();
        String email = login.getData().getEmail();
        String type = login.getData().getSource();
        SysUser sysUser = sysUserMapper.checkUserIsExist(username, nickname, type);
        Authentication authentication = null;
        LoginUser loginUser = null;
        if (sysUser != null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        } else {
            sysUser = new SysUser();
            sysUser.setUserId(null);
            sysUser.setDeptId(103L);
            sysUser.setNickName(nickname);
            sysUser.setUserName(username);
            sysUser.setEmail(email);
            sysUser.setPhonenumber(null);
            sysUser.setSex("1");
            sysUser.setAvatar(avatar);
            sysUser.setSource(source);
            sysUserMapper.insertUser(sysUser);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        }
        // 生成token
        LoginUser user = new LoginUser();
        user.setPermissions(new HashSet<String>());
        user.setUser(sysUser);
        return tokenService.createToken(user);

注意ps: 在sysuser表加一个字段source,区分第三用户,还有在SysUserMapper.xml中加入

 <result property="source" column="source"/>
   <select id="checkUserIsExist" resultType="com.ruoyi.common.core.domain.entity.SysUser">
        select *
        from sys_user
        where user_name = #{userName}
        and nick_name = #{nickName}
        and source = #{source}
    </select>

若依整合第三方登录完成

最后建议:若依版本不同,代码不同,以上代码只提供参考,不足望指出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ruoyi-cloud是一个基于Spring Cloud的开源企业级微服务框架,而mybatis-plus是一个强大的MyBatis增强工具。将两者整合可以提供更便捷的开发体验和更高效的开发效率。 下面是ruoyi-cloud整合mybatis-plus的步骤: 1. 引入依赖:在pom.xml文件中添加mybatis-plus的依赖。 ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本</version> </dependency> ``` 2. 配置数据源:在application.yml文件中配置数据源信息。 ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai username: 用户名 password: 密码 driver-class-name: com.mysql.cj.jdbc.Driver ``` 3. 配置mybatis-plus:在application.yml文件中配置mybatis-plus相关配置。 ```yaml mybatis-plus: mapper-locations: classpath*:mapper/**/*.xml global-config: db-config: id-type: auto field-strategy: not_empty logic-delete-value: 1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true cache-enabled: true ``` 4. 编写实体类和Mapper接口:在ruoyi-cloud项目中创建实体类和Mapper接口。 ```java @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String username; private String password; } @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 5. 使用mybatis-plus的CRUD操作:在Service层或Controller层中使用mybatis-plus提供的方法进行CRUD操作。 ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // 自定义业务逻辑 } ``` 至此,ruoyi-cloud就成功整合了mybatis-plus,可以使用mybatis-plus提供的强大功能进行数据库操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值