nbcio-boot如何进行gitee第三方登录

更多nbcio-boot功能请看演示系统

       gitee源代码地址

       后端代码: https://gitee.com/nbacheng/nbcio-boot

      前端代码:https://gitee.com/nbacheng/nbcio-vue.git

      在线演示(包括H5) : http://122.227.135.243:9888

1、用户gitee授权登录后可以直接绑定相应的手机号进行直接登录。

比如下面例子

/**
	 * gitee第三方绑定后直接通过admin用户返回token
	 *
	 * @param jsonObject
	 * @return
	 */
	@ApiOperation("gitee登录接口")
	@PostMapping("/bindingGitee")
	@ResponseBody
	public Result bindingGitee(@RequestBody JSONObject jsonObject) {
		Result result = new Result();
		//固定使用admin的手机号登录
		SysUser sysUser = sysUserService.getUserByPhone("13988888888");
		String token = saveToken(sysUser);
		result.setSuccess(true);
		result.setResult(token);
		return result;
	}

2、建立一个通用的gitee操作类

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Component
public class GiteeHttpClient {

	/**
     * 获取Access Token
     * post
     */
    public static JSONObject getAccessToken(String url) throws IOException {
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
//        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (null != entity) {
            String result = EntityUtils.toString(entity, "UTF-8");
            return JSONObject.parseObject(result);
        }
        httpPost.releaseConnection();
        return null;
    }

    /**
     * 获取用户信息
     * get
     */
    public static JSONObject getUserInfo1(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }

        httpGet.releaseConnection();

        return jsonObject;
    }

//    https://gitee.com/api/v5/user
    /**
     * 获取授权用户的资料
     * gitee get方式获取用户信息
     */
    public static JSONObject getUserInfo(String token,String url) throws IOException, URISyntaxException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder(url);
        builder.setParameter("access_token", token);
        HttpGet httpGet = new HttpGet(builder.build());
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }


    public static JSONArray getArray(String token,String url) throws IOException, URISyntaxException {
        JSONArray jsonArray = null;
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder(url);
        builder.setParameter("access_token", token);
        HttpGet httpGet = new HttpGet(builder.build());
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonArray = JSONObject.parseArray(result);
        }
        httpGet.releaseConnection();
        return jsonArray;
    }


    public static JSONObject put(String token,String url,JSONObject json) throws IOException, URISyntaxException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder(url);
        builder.setParameter("access_token", token);
        json.keySet().forEach((k)->{
            builder.setParameter(k,json.getString(k));
        });
        HttpPut httpPut = new HttpPut(builder.build());
        httpPut.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpPut);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }
        httpPut.releaseConnection();
        return jsonObject;
    }


    public static JSONObject post(String token,String url,JSONObject json) throws IOException, URISyntaxException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder(url);
        builder.setParameter("access_token", token);
        json.keySet().forEach((k)->{
            builder.setParameter(k,json.getString(k));
        });
        HttpPost httpPost = new HttpPost(builder.build());
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }
        httpPost.releaseConnection();
        return jsonObject;
    }
}

3、也可以考虑做一个类似下面的第三方gitee服务,如

/**
 * 第三方(GITEE)登录服务
 */
@Service
public class ThirdLoginService {
    @Autowired
    public SysUserService userService;
    @Value("${vlife.gitee.client_id}")
    public String client_id;
    @Value("${vlife.gitee.redirect_uri}")
    public String redirect_uri;
    @Value("${vlife.gitee.client_secret}")
    public String client_secret;
    @Value("${vlife.email.from}")
    public String emailFrom;
    @Value("${vlife.email.pwd}")
    public String emailPwd;


    public Boolean  openCheckCode(){
        if(StringUtils.isNotEmpty(emailFrom)&&StringUtils.isNotEmpty(emailPwd)) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获得第三方账号用户token
     * @param code
     */
    public String thirdToken(String code,String from){
        String gitToken=null;
        try {
            JSONObject jsonObject= GiteeHttpClient.getAccessToken("https://gitee.com/oauth/token?" +
                    "grant_type=authorization_code&code="+code+"&client_id="+client_id+"&redirect_uri="+redirect_uri+"&client_secret="+client_secret);
             gitToken=jsonObject.getString("access_token");
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return gitToken;
    }

    /**
     * 获得第三方用户信息
     */
    public ThirdAccountDto account(String thirdToken, String from){
        ThirdAccountDto account=null;
        try {
            JSONObject userObj=GiteeHttpClient.getUserInfo(thirdToken,"https://gitee.com/api/v5/user");
            account=new ThirdAccountDto();
            account.setId(userObj.getString("id"));
            account.setName(userObj.getString("name"));
            account.setEmail(userObj.getString("email"));
            account.setUsername(userObj.getString("login"));
            account.setThirdToken(thirdToken);
            account.setAvatar(userObj.getString("avatar_url"));
            account.setFrom(from);
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return account;
    }

    /**
     * 获得第三方用户信息
     */
    public String email(String token, String from){
        String email=null;
        try {
            JSONObject userObj=GiteeHttpClient.getArray(token,"https://gitee.com/api/v5/emails").getJSONObject(0);
            email= userObj.getString("email");
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return email;
    }


    public SysUser createUser(ThirdAccountDto accountDto){
        SysUser user=new SysUser();
//        user.setSysOrgId(sysOrgId);
        user.setSysGroupId("super");
        user.setSysDeptId("4028b8818747df52018747dfdf780000");
        user.setState("1");
//        user.setUsername(accountDto.getUsername());
        user.setThirdId(accountDto.getId());
        user.setName(accountDto.getName());
        user.setEmail(accountDto.getEmail());
        user.setSource(accountDto.getFrom());
        user.setThirdToken(accountDto.getThirdToken());
        user.setAvatar(accountDto.getAvatar());
        return user;
    }



    /* 发送验证信息的邮件 */
    public  String sendMail(String to,String code) {
        if( emailFrom==null|| emailPwd==null){
            return "邮件服务信息服务端未设置,不能发送邮件";
        }
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.163.com");
        props.put("mail.smtp.host", "smtp.163.com");
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        try {
            message.setSentDate(new Date());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            message.setFrom(new InternetAddress(emailFrom));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 加载收件人地址
            message.setSubject("低代码平台验证码","utf-8");
            Multipart multipart = new MimeMultipart(); // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
            BodyPart contentPart = new MimeBodyPart(); // 设置邮件的文本内容
            String str = "

尊敬的用户,您好!

" + "

欢迎您使用vlife低代码平台,您本次的注册码是 " + "" + code + ",10分钟之内有效,请尽快使用!

" + "

了解更多请访问vlife使用指南

" + "" + sdf.format(new Date()) + ""; contentPart.setContent(str, "text/html;charset=utf-8"); multipart.addBodyPart(contentPart); message.setContent(multipart); message.saveChanges(); // 保存变化 Transport transport = session.getTransport("smtp"); // 连接服务器的邮箱 transport.connect("smtp.163.com", emailFrom, emailPwd); // 把邮件发送出去 transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { e.printStackTrace(); return "发送失败:"+e.getMessage(); } return null; } }

你可能感兴趣的:(nbcio-boot,flowable,java开发,flowable,nbcio-boot,jeecg-boot)