Last active
August 16, 2023 13:37
-
-
Save bengsiswantoh/8c75fe83678dde291a7606fee674c7b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ArticlesController < ApplicationController | |
before_action :require_login, only: :new | |
SECRET = "yoursecretword" | |
def index | |
payload = { data: 'test' } | |
token = JWT.encode payload, SECRET, "HS256" | |
render json: { token: token } | |
end | |
def new | |
render json: { message: "success" } | |
end | |
private | |
def login_with_jwt? | |
# token = "eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.CvmX7lDrNgkitaKRLg0C__91OBGo3SQBG56X3VY9cEg" | |
valid_token = false | |
begin | |
token = request.headers["jwt"] | |
if token | |
data = JWT.decode request.headers["jwt"], SECRET, true, { algorithm: "HS256" } | |
# selain cek valid token bisa di cek isi dari payloadnya | |
if data | |
valid_token = true | |
end | |
end | |
rescue => e | |
end | |
valid_token | |
end | |
def require_login | |
unless user_signed_in? || login_with_jwt? | |
render json: { message: "You must be logged in to access this section" } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment