diff --git a/app/controllers/v1/base_controller.rb b/app/controllers/v1/base_controller.rb index d30b586..35f9e28 100644 --- a/app/controllers/v1/base_controller.rb +++ b/app/controllers/v1/base_controller.rb @@ -6,6 +6,8 @@ def auth_user "Please sign in", "Please sign in" ) and return unless current_user + + end def message_success(message, content) diff --git a/app/controllers/v1/sessions_controller.rb b/app/controllers/v1/sessions_controller.rb index 90fe95a..b008176 100644 --- a/app/controllers/v1/sessions_controller.rb +++ b/app/controllers/v1/sessions_controller.rb @@ -10,11 +10,9 @@ def create ) and return unless user.valid_password?(session_params[:password]) sign_in(user) - - render json: message_success( - "Sign in successfully", - "Sign in successfully" - ) + user.send(:generate_token) + + render json: message_success("Sign in successfully", {api_token: user.api_token}) end def destroy diff --git a/app/controllers/v1/users_controller.rb b/app/controllers/v1/users_controller.rb index 066aabb..6616837 100644 --- a/app/controllers/v1/users_controller.rb +++ b/app/controllers/v1/users_controller.rb @@ -2,7 +2,7 @@ class V1::UsersController < V1::BaseController def create user = User.create!(user_params) - render json: message_success("Sign up successfully", user) + render json: message_success("Sign up successfully", {api_token: user.api_token}) end private diff --git a/app/models/user.rb b/app/models/user.rb index d2e5813..6324274 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -6,4 +6,16 @@ class User < ActiveRecord::Base has_many :posts has_many :comments + + before_create :generate_token + + private + def time_expire + (Time.current + 30.days).to_i + end + + def generate_token + self.api_token = SecureRandom.urlsafe_base64(nil, false) + self.expire_at = time_expire + end end diff --git a/db/migrate/20150917165426_add_api_token_and_expire_at_to_users.rb b/db/migrate/20150917165426_add_api_token_and_expire_at_to_users.rb new file mode 100644 index 0000000..3947869 --- /dev/null +++ b/db/migrate/20150917165426_add_api_token_and_expire_at_to_users.rb @@ -0,0 +1,6 @@ +class AddApiTokenAndExpireAtToUsers < ActiveRecord::Migration + def change + add_column :users, :api_token, :string + add_column :users, :expire_at, :integer + end +end diff --git a/db/schema.rb b/db/schema.rb index 841b108..30ae813 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20150917162231) do +ActiveRecord::Schema.define(version: 20150917165426) do create_table "comments", force: :cascade do |t| t.string "content", limit: 255 @@ -47,6 +47,8 @@ t.string "last_sign_in_ip", limit: 255 t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.string "api_token", limit: 255 + t.integer "expire_at", limit: 4 end add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree