Skip to content

Commit

Permalink
Add user info API
Browse files Browse the repository at this point in the history
  • Loading branch information
qichunren committed Jan 15, 2024
1 parent 22ea9ae commit ad4e7d1
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 101 deletions.
57 changes: 4 additions & 53 deletions app/controllers/qweixin/users_controller.rb
Original file line number Diff line number Diff line change
@@ -1,60 +1,11 @@
module Qweixin
class UsersController < ApplicationController
before_action :set_user, only: %i[ show edit update destroy ]
skip_before_action :verify_authenticity_token
before_action :require_auth_token!, only: %i[ show ]

# GET /users
def index
@users = User.all
end

# GET /users/1
# GET /weixin/user
def show
render json: { errcode: 0, errmsg: "ok", user_info: @current_user.as_json(only: %i[ id nickname mobile avatar ]) }
end

# GET /users/new
def new
@user = User.new
end

# GET /users/1/edit
def edit
end

# POST /users
def create
@user = User.new(user_params)

if @user.save
redirect_to @user, notice: "User was successfully created."
else
render :new, status: :unprocessable_entity
end
end

# PATCH/PUT /users/1
def update
if @user.update(user_params)
redirect_to @user, notice: "User was successfully updated.", status: :see_other
else
render :edit, status: :unprocessable_entity
end
end

# DELETE /users/1
def destroy
@user.destroy!
redirect_to users_url, notice: "User was successfully destroyed.", status: :see_other
end

private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end

# Only allow a list of trusted parameters through.
def user_params
params.require(:user).permit(:session_key, :unionid, :openid, :last_appid)
end
end
end
3 changes: 2 additions & 1 deletion config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
Qweixin::Engine.routes.draw do
resources :users
resource :user

get "app_login", to: "sessions#code2session"
get "app_checksession", to: "sessions#checksession"
end
4 changes: 4 additions & 0 deletions db/migrate/20240111055137_create_qweixin_users.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
class CreateQweixinUsers < ActiveRecord::Migration[7.1]
def change
create_table :qweixin_users do |t|
t.string :nickname
t.string :mobile
t.string :avatar

t.string :session_key
t.string :unionid
t.string :openid
Expand Down
19 changes: 18 additions & 1 deletion lib/qweixin/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
module Qweixin
class Client
include ActiveSupport::Configurable
attr_accessor :access_token

# https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
# 获取接口调用凭据
Expand All @@ -19,7 +20,9 @@ def getAccessToken
# https://docs.ruby-lang.org/en/master/Net/HTTP.html

response = Net::HTTP.get(api_uri)
JSON.parse(response)
response_json = JSON.parse(response) rescue {}
self.access_token = response_json["access_token"]
response_json
end

# https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
Expand All @@ -44,5 +47,19 @@ def code2session(js_code:)
# puts "weixin response: #{response}"
JSON.parse(response) rescue {}
end

# DOC: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/checkSessionKey.html
# GET https://api.weixin.qq.com/wxa/checksession?access_token=ACCESS_TOKEN
def checksession(access_token:)
raise "access_token is required!" if access_token.blank?

api_uri = URI("https://api.weixin.qq.com/wxa/checksession?access_token=#{access_token}")
# https://docs.ruby-lang.org/en/master/Net/HTTP.html

response = Net::HTTP.get(api_uri)
# puts "weixin response: #{response}"
JSON.parse(response) rescue {}
end

end
end
12 changes: 0 additions & 12 deletions test/controllers/qweixin/token_controller_test.rb

This file was deleted.

57 changes: 23 additions & 34 deletions test/controllers/qweixin/users_controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,45 +8,34 @@ class UsersControllerTest < ActionDispatch::IntegrationTest
@user = qweixin_users(:one)
end

test "should get index" do
get users_url
test "should get not user json without auth token" do
get user_url
assert_response :success
end

test "should get new" do
get new_user_url
assert_response :success
end

test "should create user" do
assert_difference("User.count") do
post users_url, params: { user: { last_appid: @user.last_appid, openid: @user.openid, session_key: @user.session_key, unionid: @user.unionid } }
assert_equal "{\"errcode\":10000,\"errmsg\":\"user not found\"}", response.body
end

test "should get not user json after app login" do
valid_code = "AAAABBCCCCMDpR1Qnl111rS1rY3C5i1c"
net_http_mock = Minitest::Mock.new
mocked_response = '{"session_key":"AAASrAB+K5Y1u44y4jNsjQ==","openid":"#{SecureRandom.hex}"}'
mocked_arg = URI("https://api.weixin.qq.com/sns/jscode2session?appid=#{Qweixin::Client.config.appid}&secret=#{Qweixin::Client.config.secret}&js_code=#{valid_code}&grant_type=authorization_code")
net_http_mock.expect(:call, mocked_response, [mocked_arg])

Net::HTTP.stub(:get, net_http_mock) do
# send request with auth token in header
get "/weixin/app_login?code=#{valid_code}"
assert_response :success

# get user_url request, with auth token in header
token = User.last.generate_auth_token
get user_url, headers: { 'Authorization' => token }
result_json = JSON.parse(response.body)
assert_equal ["errcode", "errmsg", "user_info"], result_json.keys
assert_equal ["id", "nickname", "mobile", "avatar"], result_json["user_info"].keys
end

assert_redirected_to user_url(User.last)
end

test "should show user" do
get user_url(@user)
assert_response :success
end

test "should get edit" do
get edit_user_url(@user)
assert_response :success
end

test "should update user" do
patch user_url(@user), params: { user: { last_appid: @user.last_appid, openid: @user.openid, session_key: @user.session_key, unionid: @user.unionid } }
assert_redirected_to user_url(@user)
end

test "should destroy user" do
assert_difference("User.count", -1) do
delete user_url(@user)
end

assert_redirected_to users_url
end
end
end
3 changes: 3 additions & 0 deletions test/dummy/db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@

ActiveRecord::Schema[7.1].define(version: 2024_01_11_055137) do
create_table "qweixin_users", force: :cascade do |t|
t.string "nickname"
t.string "mobile"
t.string "avatar"
t.string "session_key"
t.string "unionid"
t.string "openid"
Expand Down
6 changes: 6 additions & 0 deletions test/fixtures/qweixin/users.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

one:
nickname: "Weixin User1"
mobile: "13800138000"
avatar: "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJ"
session_key: MyString
unionid: MyString
openid: MyString
last_appid: MyString

two:
nickname: "Weixin User2"
mobile: "13800138111"
avatar: "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJ"
session_key: MyString
unionid: MyString
openid: MyString
Expand Down

0 comments on commit ad4e7d1

Please sign in to comment.