64 lines
2.0 KiB
Ruby
64 lines
2.0 KiB
Ruby
#coding=utf-8
|
||
#
|
||
class OschinaController < ApplicationController
|
||
|
||
CLIENT_ID = 'e5da9855f89bc724a335d100cb63cf02a03a592bd3151bbc84acf7b2e222ddb8'
|
||
CLIENT_SECRET = '4f2f291fac1d3dae338c18a3e3544814be5a1c4ade9e72d62f45ceab914c89f5'
|
||
ROOT_URl = Redmine::Configuration['oschina_oauth_cburl'] || 'https://www.trustie.net'
|
||
OSCHINA_URL = 'https://gitee.com'
|
||
|
||
def login
|
||
# 根据session,看看有没有存access_token,去刷新下。
|
||
# 1. 如果过期,则跳转
|
||
# 2. 未过期,直接用
|
||
|
||
redirect_to "#{OSCHINA_URL}/oauth/authorize?client_id=#{CLIENT_ID}&redirect_uri=#{ROOT_URl}/oschina/login_cb&response_type=code"
|
||
end
|
||
|
||
def login_callback
|
||
#获取code
|
||
#
|
||
#
|
||
logger.debug params
|
||
url = "#{OSCHINA_URL}/oauth/token?grant_type=authorization_code"+
|
||
"&code=#{params[:code]}&client_id=#{CLIENT_ID}&redirect_uri=#{ROOT_URl}/oschina/login_cb&client_secret=#{CLIENT_SECRET}"
|
||
|
||
res = post(url)
|
||
logger.debug res
|
||
|
||
body = decode(res)
|
||
#{"access_token":"21a80f20ff736b54aecd002b60210943","token_type":"bearer","expires_in":86400,"refresh_token":"be92e2c137a8c6dd22f0d8c4a622b3aeceb054087a95d293130f04ec60fd3e3f","scope":"user_info","created_at":1542684088}
|
||
raise '登录失败' unless body["access_token"]
|
||
|
||
#获取此用户信息
|
||
res = get("#{OSCHINA_URL}/api/v5/user?access_token=#{body["access_token"]}")
|
||
logger.debug res
|
||
info = decode(res)
|
||
|
||
oschina = Oschina.find_by_oschina_id(info["id"])
|
||
unless oschina
|
||
#新建用户
|
||
ActiveRecord::Base.transaction do
|
||
user = User.create_with_oschina!(info)
|
||
oschina = Oschina.create_with_info!(info, user)
|
||
end
|
||
end
|
||
|
||
self.logged_user = oschina.user
|
||
|
||
user = UserExtensions.where(:user_id => User.current.id).first
|
||
if user.gender.nil? || user.school_id.nil? || User.current.lastname.nil?
|
||
redirect_to my_account_path
|
||
elsif user.identity == 3 && user.school_id.nil?
|
||
redirect_to my_account_path
|
||
else
|
||
redirect_to User.current
|
||
end
|
||
|
||
end
|
||
|
||
|
||
private
|
||
include Trustie::Http
|
||
|
||
end |