DanKim0213 / Today-I-Learned

Today I Learned
1 stars 0 forks source link

Tools #14

Open DanKim0213 opened 1 year ago

DanKim0213 commented 1 year ago

Tools

DanKim0213 commented 10 months ago

Graphql

DanKim0213 commented 10 months ago

ESLint

DanKim0213 commented 10 months ago

Kakao oauth

  1. do you know how to implement kakao oauth?
  2. what is the difference between javascript implementation and rest api implementation in kakao login
  3. According to the kakao developers reference, https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api, a service server requests to kakao oauth server by /oauth/authorize. Is this correct?
  4. For the user to be redirected to the Kakao login page, they should request from the cliend side, not from service server, isn't it?
  5. Could you give me an example of being implemented by react in client side and express in server side?
  6. What can I do with this access token?
  7. Then I wonder if it is okay that users bring access token rather than the backend server?
  8. For security, you should have returned an access token generated by your own backend server, for example jwt, rather than retuning the kakao oauth access token itself right?

1. do you know

Yes, I can provide you with a general overview of how to implement Kakao OAuth.

  1. Register your application on the Kakao Developers website and obtain your API keys.

  2. Set up a redirect URI for your application, where the authorization code will be returned after the user grants access.

  3. Include the Kakao JavaScript SDK in your web application.

  4. Create a Kakao login button on your web page and use the SDK to handle user authentication.

  5. When the user logs in successfully, you will receive an authorization code in the redirect URI that you specified earlier.

  6. Use the authorization code to request an access token from the Kakao API server.

  7. Once you have the access token, you can use it to call Kakao API endpoints to retrieve user data or perform other actions on behalf of the user.

Here's some sample code to give you an idea of what the implementation might look like:

// Load the Kakao JavaScript SDK
Kakao.init('YOUR_APP_KEY');

// Create a Kakao login button
Kakao.Auth.createLoginButton({
  container: '#kakao-login-btn',
  success: function(authObj) {
    // Handle successful login
    var code = authObj.code;
    // Use the code to request an access token from the Kakao API server
    // ...
  },
  fail: function(err) {
    // Handle login failure
    console.log(err);
  }
});

Note that this is just a simplified example, and you will need to customize the code to fit your specific application requirements.

2. what is the diff

The difference between JavaScript implementation and REST API implementation of Kakao login lies in the way the authentication flow is handled.

JavaScript implementation involves using the Kakao JavaScript SDK to provide a Kakao login button on your website or web application. When the user clicks on the login button, the SDK handles the authentication flow and returns an access token that you can use to call Kakao API endpoints. This approach is typically used for web-based applications.

On the other hand, REST API implementation involves making direct API requests to the Kakao API server to perform the authentication flow. This approach can be used for both web-based and native applications. In this approach, you will need to implement the entire authentication flow yourself, which includes redirecting the user to the Kakao login page, obtaining an authorization code, exchanging the code for an access token, and storing the access token securely.

While both approaches achieve the same end goal of authenticating users with Kakao, the choice of implementation depends on the type of application you are building and the specific requirements of your project. If you are building a web-based application, using the JavaScript SDK is generally easier and more convenient, while REST API implementation may be more appropriate for native applications or scenarios where you need more fine-grained control over the authentication flow.

3. According to

Yes, that's correct. According to the Kakao developers reference, when implementing Kakao login using the REST API, the service server sends a request to the Kakao OAuth server's /oauth/authorize endpoint to initiate the authentication flow.

This endpoint is used to request authorization from the user for your application to access their Kakao account information. The user is redirected to the Kakao login page, where they enter their Kakao credentials and grant permission to your application to access their data.

After the user grants permission, the OAuth server will redirect the user back to your service server's specified redirect URI with an authorization code. Your service server then uses this authorization code to request an access token from the Kakao OAuth server's /oauth/token endpoint, which can be used to make API calls to retrieve user information.

It's important to follow the proper authentication flow and handle errors appropriately to ensure the security and reliability of your application. The Kakao developers documentation provides more detailed information and examples on how to implement Kakao login using the REST API.

4. For the user

Yes, that's correct. When using the Kakao REST API to implement login, the user's browser should initiate the request to the Kakao login page, not the service server.

Here's a general overview of how the authentication flow should work:

  1. When the user clicks on the login button on your web page, your client-side code should make a request to your service server's /login endpoint.

  2. Your service server should respond with a redirect to the Kakao OAuth server's /oauth/authorize endpoint, passing along any necessary parameters (such as your application ID and the redirect URI).

  3. The user's browser will be redirected to the Kakao login page, where they can enter their Kakao credentials and grant permission for your application to access their information.

  4. After the user grants permission, the Kakao OAuth server will redirect the user's browser back to your specified redirect URI with an authorization code.

  5. Your client-side code can then retrieve the authorization code from the URL and make a request to your service server's /token endpoint to exchange the code for an access token.

  6. Your service server should then respond with the access token, which your client-side code can use to make API calls to retrieve user information.

It's important to note that the specific implementation details may vary depending on your application's requirements and the framework you're using. The Kakao developers documentation provides more detailed information and examples on how to implement Kakao login using the REST API.

5. Could you give me

Sure, here's an example of implementing Kakao login using React on the client side and Express on the server side:

Client-side (React):

import React, { useState } from "react";
import axios from "axios";

function KakaoLogin() {
  const [accessToken, setAccessToken] = useState(null);

  const handleLoginClick = async () => {
    const res = await axios.get("/login");
    window.location = res.data.redirectUrl;
  };

  const handleTokenClick = async () => {
    const res = await axios.post("/token", {
      authorizationCode: new URLSearchParams(window.location.search).get("code"),
    });
    setAccessToken(res.data.accessToken);
  };

  return (
    <div>
      {accessToken ? (
        <div>
          Access Token: {accessToken}
        </div>
      ) : (
        <div>
          <button onClick={handleLoginClick}>Kakao Login</button>
          {window.location.search.includes("code") && (
            <button onClick={handleTokenClick}>Get Access Token</button>
          )}
        </div>
      )}
    </div>
  );
}

export default KakaoLogin;

This code creates a KakaoLogin component that displays a button to initiate the Kakao login flow. When the button is clicked, the client-side code makes a GET request to the server's /login endpoint, which returns a redirect URL to the Kakao login page. The client-side code then redirects the user's browser to the login page.

After the user logs in and grants permission, the Kakao OAuth server will redirect the user's browser back to the server's specified redirect URI with an authorization code. The client-side code retrieves the authorization code from the URL and sends a POST request to the server's /token endpoint to exchange the code for an access token. The server responds with the access token, which the client-side code stores in state.

Server-side (Express):

const express = require("express");
const axios = require("axios");
const qs = require("querystring");

const app = express();
const PORT = 3000;

const CLIENT_ID = "YOUR_CLIENT_ID";
const CLIENT_SECRET = "YOUR_CLIENT_SECRET";
const REDIRECT_URI = "http://localhost:3000/token";

app.get("/login", (req, res) => {
  const redirectUrl = `https://kauth.kakao.com/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code`;
  res.json({ redirectUrl });
});

app.post("/token", async (req, res) => {
  const { authorizationCode } = req.body;
  const tokenRequestConfig = {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
    },
  };
  const tokenRequestBody = qs.stringify({
    grant_type: "authorization_code",
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    redirect_uri: REDIRECT_URI,
    code: authorizationCode,
  });
  try {
    const tokenResponse = await axios.post(
      "https://kauth.kakao.com/oauth/token",
      tokenRequestBody,
      tokenRequestConfig
    );
    const { access_token } = tokenResponse.data;
    res.json({ accessToken: access_token });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Failed to get access token" });
  }
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

This code sets up an Express server with two endpoints: /login and /token. The /login endpoint returns a redirect URL

6. What can I do with this access token?

With the access token, you can make API calls to Kakao APIs on behalf of the user who authorized the token.

For example, with the access_token, you can make requests to the Kakao REST APIs to get the user's profile information, their friends list, and send messages to their KakaoTalk friends, etc.

Here's an example of how to make an API call to get the user's Kakao account information using the access_token in Node.js:

const axios = require("axios");

const getKakaoAccountInfo = async (accessToken) => {
  try {
    const response = await axios.get("https://kapi.kakao.com/v2/user/me", {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  } catch (err) {
    console.error(err);
    throw new Error("Failed to get Kakao account info");
  }
};

// Example usage:
const accessToken = "YOUR_ACCESS_TOKEN";
const accountInfo = await getKakaoAccountInfo(accessToken);
console.log(accountInfo);

This code makes a GET request to the Kakao REST API endpoint for getting the user's account information. The Authorization header includes the access_token retrieved from the OAuth flow. The response.data object contains the user's account information, which is returned by the API in JSON format.

Note that the specific APIs available to you depend on the scope of the authorization you requested during the OAuth flow. For example, if you requested the talk_message scope, you would be able to send messages to the user's KakaoTalk friends using the API.

7. Then I wonder if it is okay that users bring access token rather than the backend server?

It's generally not recommended to have users pass access tokens directly from the frontend to backend, as this could potentially expose the access token to attackers. The access token is a sensitive piece of information that should be kept secure.

Instead, it's recommended to have the frontend send a request to the backend server to perform the API call with the access token. The backend server can then securely store the access token and use it to make API requests on behalf of the user.

In the example I provided earlier, the access token is passed from the backend server to the client-side React code as a response to the OAuth flow. The client-side code then sends the access token back to the server for API requests, rather than holding onto the token itself. This approach is more secure, as the access token is never exposed to attackers on the client-side.

8. For security, you should have returned an access token generated by your own backend server, for example jwt, rather than retuning the kakao oauth access token itself right?

Yes, that's correct. For security reasons, it's recommended to generate and return your own access token instead of returning the Kakao OAuth access token directly to the client-side code.

This approach has several benefits:

  1. Access tokens generated by your own backend server can be encrypted and signed to prevent tampering or unauthorized access, making them more secure.

  2. You can control the lifetime of the access token generated by your server, and you can revoke it at any time if necessary.

  3. You can include additional information in the access token, such as user roles or permissions, which can be used for authorization purposes when making API requests.

Here's an example of how you can generate and return a JWT access token using the jsonwebtoken library in a Node.js Express app:

const jwt = require('jsonwebtoken');

// Generate a JWT token with a payload containing the user ID and any other relevant information
const generateAccessToken = (userId, expiresIn) => {
  const payload = {
    userId: userId,
    expires: Date.now() + expiresIn,
    // Add any additional information to the payload here
  };
  return jwt.sign(payload, process.env.JWT_SECRET);
};

// Endpoint to handle the Kakao OAuth callback and generate a JWT access token
app.get('/auth/kakao/callback', async (req, res) => {
  // Use the code from the Kakao OAuth flow to retrieve the Kakao access token
  const { code } = req.query;
  const { access_token } = await getKakaoAccessToken(code);

  // Use the Kakao access token to retrieve the user ID and any other relevant information
  const { id } = await getKakaoUserId(access_token);

  // Generate a JWT access token with the user ID and set the "Authorization" header in the response
  const accessToken = generateAccessToken(id, 86400); // Set the token expiration time to 24 hours
  res.setHeader('Authorization', `Bearer ${accessToken}`);

  // Redirect the user to the desired page
  res.redirect('/dashboard');
});

In this example, the generateAccessToken function generates a JWT access token with a payload containing the user ID and any other relevant information. The JWT_SECRET environment variable is used to sign the token.

After generating the access token, the server sets the "Authorization" header in the response with the Bearer prefix and the JWT access token. The client-side code can then extract the access token from the response header and include it in subsequent API requests to the server.

DanKim0213 commented 10 months ago

TIL Script

I think TIL script is very useful to make a summary.

Let's create TIL script with Github action:

DanKim0213 commented 10 months ago

Vite open in a specific browser

According to Vite Server Options - open:

Automatically open the app in the browser on server start. [...] If you want to open the server in a specific browser you like, you can set the env process.env.BROWSER (e.g. firefox).

There are two ways to open a specific browser when using Vite:

According to openapp:

The app name is platform dependent. For example, Chrome is google chrome on macOS, google-chrome on Linux and chrome on Windows.

Therefore, precess.env.BROWSER=google chrome or process.env.BROWSER=safari works.

DanKim0213 commented 9 months ago

How to embed Video into Markdown

Here’s a quick guide how this can be done on MacOS:

  1. Open QuickTime Player. Select File->New Screen Recording
  2. Record a demo. It will be recorded with the .mov extension
  3. Create a new markdown file in GitHub.
  4. Click on the edit this file in the web interface
  5. Drag and drop your file into the editing area
  6. Video will be automatically converted and new https://user-images.githubusercontent.com/... link will be pasted into the markdown file
  7. Embed video with tags ![name](link) for readme, or to the <video tags for blog:

References:

DanKim0213 commented 9 months ago

Yarn

What problems does Yarn solve?

https://yarnpkg.com https://yarnpkg.com/getting-started/qa#which-files-should-be-gitignored https://yarnpkg.com/blog/bun

DanKim0213 commented 7 months ago

How to make a Progressive Web App (PWA) for android, iOS, and Web

Create an Ionic React App: Framework and Documentation

DanKim0213 commented 6 months ago

.env file not shown by nvim tree

normal H toggles dotfiles normal I toggles gitignore

reference

DanKim0213 commented 4 months ago

VIM

https://stackoverflow.com/a/426910

Since CTRLV is used to paste, you can't use it to start a blockwise Visual selection. You can use CTRLQ instead. You can also use CTRLQ in Insert mode and Command-line mode to get the old meaning of CTRLV. But CTRLQ doesn't work for terminals when it's used for control flow.

DanKim0213 commented 4 months ago

Callout

https://github.com/orgs/community/discussions/16925

[!NOTE]
Highlights information that users should take into account, even when skimming.

[!TIP] Optional information to help a user be more successful.

[!IMPORTANT]
Crucial information necessary for users to succeed.

[!WARNING]
Critical content demanding immediate user attention due to potential risks.

[!CAUTION] Negative potential consequences of an action.