投稿時間:2023-05-28 06:09:07 RSSフィード2023-05-28 06:00 分まとめ(13件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
js JavaScriptタグが付けられた新着投稿 - Qiita sort()メソッドで大文字と小文字を分けずにソートさせる方法 https://qiita.com/yuta-10112022/items/4a4ec44378bb1e01a217 nctionstletastolocalelow 2023-05-28 05:45:37
海外TECH MakeUseOf What Is a Niche? How to Find Yours as a Content Creator https://www.makeuseof.com/how-to-find-niche-as-content-creator/ chance 2023-05-27 20:30:19
海外TECH MakeUseOf How to Create an AI Voice That Sounds Like You With ElevenLabs https://www.makeuseof.com/how-to-create-an-ai-voice-that-sounds-like-you-with-elevenlabs/ create 2023-05-27 20:15:18
海外TECH DEV Community How to use Firebase Authentication in Next.js 13, Server Side with Admin SDK https://dev.to/geiel/how-to-use-firebase-authentication-in-nextjs-13-client-and-server-side-1bbn How to use Firebase Authentication in Next js Server Side with Admin SDKI m new to this world of Full Stack Frameworks like Next js SvelteKit Remix But I know all the advantages it has so I wanted to use it to create a project I m working on I love Firebase and I wanted to have it in the project because it just has everything I need for almost any project the problem I had is that Next js although it is great the update to version is something recent so it was difficult to find information about integrating Firebase Authentication in Next js so in this tutorial I will show how to implement Firebase with Next js Install Firebase and Firebase Admin SDKnpm install firebase firebase adminThere are many ways to manage authentication with Firebase I will give you the basics so that you can implement it as you wish in your application First we need to get our private key from firebaseIn order to access to firebase from the server and use the Admin SDK we need to generate a private key from Google Go to Project Overview then Project settingsGo to Service accounts Firebase Admin SDK then Generate new private keyFirebase will give you json file with you credentialsNow with you credentials we can go the Next js project Configure Firebase Admin SDKCreate a lib firebase admin config ts file in the project base routeimport initializeApp getApps cert from firebase admin app const firebaseAdminConfig credential cert process env FIREBASE SECRET KEY export function customInitApp if getApps length lt initializeApp firebaseAdminConfig The FIREBASE SECRET KEY is the file location that we download from firebase if you don t want to use the file you can pass the credentials directly like this const firebaseAdminConfig credential cert projectId project id property from the file clientEmail client email property from the file privateKey private key property from the file With this file we have the Firebase Admin SDK configured in our project Now let s configure our Firebase web app Configure Firebase Web AppCreate a lib firebase config ts file in the project base routeimport initializeApp from firebase app import getApps getApp from firebase app import getAuth from firebase auth import GoogleAuthProvider from firebase auth const firebaseConfig apiKey process env FIREBASE API KEY authDomain process env FIREBASE AUTH DOMAIN projectId process env FIREBASE PROJECT ID storageBucket process env FIREBASE STORAGE BUCKET messagingSenderId process env FIREBASE MESSAGING SENDER ID appId process env FIREBASE APP ID measurementId process env FIREBASE MEASUREMENT ID const app getApps length gt getApp initializeApp firebaseConfig const auth getAuth app const provider new GoogleAuthProvider export auth provider You can find all those configuration in the Firebase Console go the Firebase documentation for more information Im using the Google Provider to authenticate users but you can use whatever firebase offer Now the main reason why I m doing this tutorial is basically to let you know how to authenticate users in the server side using only Firebase so let s get started You can use Route Handlers to manage the user session in the server Sign In user with Firebase Sign In in the clientCreate a app login page tsx fileHere we are gonna use Firebase to Sign In with Google and get the token id that later we are gonna send to the server use client import getRedirectResult signInWithRedirect from firebase auth import auth provider from lib firebase import useEffect useState from react import useRouter from next navigation export default function SignIn const router useRouter useEffect gt getRedirectResult auth then async userCred gt if userCred return fetch api login method POST headers Authorization Bearer await userCred user getIdToken then response gt if response status router push protected function signIn signInWithRedirect auth provider return lt gt lt button onClick gt signIn gt Sign In lt button gt lt gt Sign In in the serverCreate a app api login route tsx fileHere we are gonna handle the users sessions and authorize it using Firebase Adminimport auth from firebase admin import customInitApp from lib firebase admin config import cookies headers from next headers import NextRequest NextResponse from next server Init the Firebase SDK every time the server is calledcustomInitApp export async function POST request NextRequest response NextResponse const authorization headers get Authorization if authorization startsWith Bearer const idToken authorization split Bearer const decodedToken await auth verifyIdToken idToken if decodedToken Generate session cookie const expiresIn const sessionCookie await auth createSessionCookie idToken expiresIn const options name session value sessionCookie maxAge expiresIn httpOnly true secure true Add the cookie to the browser cookies set options return NextResponse json status With this you already have the user logged in with Firebase using Google now the advantage of using this approach is that you have access to the session cookie which is basically the token of the logged user and you can access it from the server so if you need to SSR and authenticate the user you can do it How to authenticate a user in the serverYou can create in the same app api login route tsx file a new method to check if the user is authenticated or notexport async function GET request NextRequest const session cookies get session value Validate if the cookie exist in the request if session return NextResponse json isLogged false status Use Firebase Admin to validate the session cookie const decodedClaims await auth verifySessionCookie session true if decodedClaims return NextResponse json isLogged false status return NextResponse json isLogged true status Now you can call this method anywhere in your app for example in the middleware ts file Validate user session in the middleware tsimport NextResponse from next server import type NextRequest from next server export async function middleware request NextRequest response NextResponse const session request cookies get session Return to login if don t have a session if session return NextResponse redirect new URL login request url Call the authentication endpoint const responseAPI await fetch api login headers Cookie session session value Return to login if token is not authorized if responseAPI status return NextResponse redirect new URL login request url return NextResponse next Add your protected routesexport const config matcher protected path Sign out a userIf your cookies are httpOnly the only way to delete them is on the server so you can create a handler for that import cookies from next headers import NextRequest NextResponse from next server export async function POST request NextRequest Remove the value and expire the cookie const options name session value maxAge cookies set options return NextResponse json status Now in the client you can call that endpointimport auth from lib firebase import signOut from firebase auth async function signOutUser Sign out with the Firebase client await signOut auth Clear the cookies in the server const response await fetch http localhost api signOut method POST if response status router push login ConclusionNow with this you have the bases to be able to authenticate with Firebase anywhere in your application you can implement this to your liking since Firebase Admin gives you the flexibility to do it here is only one but I am sure that you can implement something even better and that suits your situation 2023-05-27 20:20:49
海外TECH DEV Community State Of CSS, May 2023 : Newest Additions https://dev.to/basheerdotdev/state-of-css-may-2023-newest-additions-1p3o State Of CSS May Newest AdditionsState of CSS Newest Additions May CSS has come a long way in recent years and the state of CSS in is more exciting than ever before With numerous new features and enhancements introduced in web developers now have a plethora of new CSS tricks up their sleeves In this comprehensive guide we will delve into the most pertinent and innovative additions to CSS in exploring the latest features that are revolutionizing web design and development Container Queries The Future of Responsive Design Container Queries BasicsOne of the most significant advancements in the state of CSS is the introduction of Container Queries This powerful feature allows developers to modify an element s appearance and behavior based on its container rather than the viewport size This provides a more flexible and context aware approach to responsive design enabling components to adapt seamlessly to various environments such as headers sidebars or modals Container Query UnitsAnother exciting addition to container queries is the introduction of container query units These units enable developers to implement responsive typography by listening to the container s width height inline size block size or the smaller or larger value of these dimensions Although full browser support has yet to be achieved the introduction of container query units promises to unlock new possibilities for responsive design focus visible Pseudo Class Improved Accessibility with Better Focus Indicators focus visible is a new pseudo class that significantly improves accessibility by intelligently displaying focus indicators based on user input This feature ensures that focus indicators are only shown when needed such as for keyboard users who rely on them for navigation By making focus indicators context aware focus visible enhances the user experience for both keyboard and mouse users without compromising accessibility has Selector The Power of Relational SelectorsThe has selector is a groundbreaking addition to the state of CSS This relational selector enables developers to apply styles conditionally based on the presence of specific child elements or their states The versatility of the has selector allows for a wide range of use cases from parent selection to sibling and child element targeting Combining has with Other Pseudo ClassesThe has selector can be combined with other pseudo classes such as is where and not to create even more powerful and dynamic CSS rules These combinations unlock endless possibilities for conditional styling making the has selector a game changer in the world of CSS Subgrid Nested Grids for Seamless AlignmentThe introduction of the subgrid feature in CSS Grid Layout has resolved a long standing issue with nested grids With subgrid developers can effortlessly align inner grids with their parent grid ensuring seamless and consistent layouts This feature also supports endless nesting allowing for complex and versatile grid structures Accent Color Customizing Form Elements Made EasyStyling form elements has always been challenging often requiring external libraries or packages to achieve even the simplest of customizations However the accent color property has changed the game allowing developers to easily customize the appearance of user interface controls such as checkboxes radio buttons and progress bars This newfound control over form elements is a welcome addition to the state of CSS in Individual Transform Properties Enhanced Control Over TransformationsThe introduction of individual transform properties has made it easier than ever to apply and modify CSS transformations With individual properties for scale translate and rotate developers no longer need to define the entire transform declaration when making changes to a single property This enhancement optimizes the process of creating and modifying animations and transitions making it an essential new CSS trick for web developers Wide Gamut Color Spaces Expanding the Web Color PaletteThe arrival of wide gamut color spaces has considerably expanded the web color palette enabling developers to create more vivid and vibrant designs With new color spaces such as REC P XYZ LAB OKLAB LCH and OKLCH web developers can now achieve a broader range of colors in their designs bringing a new level of richness and depth to web content New Viewport Units Solving Full Viewport Sizing IssuesAccurate and consistent full viewport sizing has long been a challenge for web developers particularly on mobile devices Fortunately the introduction of new viewport units has resolved many of these issues providing developers with a more reliable and precise method for sizing elements based on the viewport With units such as small viewport height and width svh and svw large viewport height and width lvh and lvw and dynamic viewport height and width dvh and dvw developers can now achieve more accurate and consistent full viewport sizing Text Wrap Balance Smarter Typography for Headlines and Titlestext wrap balance is a fantastic new feature that improves typography for headings and titles By balancing text across multiple lines text wrap balance ensures that headings and titles maintain a visually appealing and readable format This feature is particularly useful for responsive designs where text must adapt to various screen sizes and layouts Initial Letter Enhanced Control Over Drop CapsThe initial letter property has brought better control over drop cap styling to the state of CSS in This property allows developers to define the size and position of the first letter in a paragraph creating eye catching and unique drop caps With improved control over drop cap styling web developers can craft more engaging and visually appealing content ConclusionThe state of CSS in is more exciting and innovative than ever before The introduction of groundbreaking features such as container queries the has selector and wide gamut color spaces alongside enhancements to existing features like viewport units and transform properties has significantly expanded the possibilities for web developers As we continue to explore and master these new CSS tricks the future of web design and development looks brighter and more dynamic than ever before I m coming with some detailed and down to earth practical tutorials on these Follow me for more content and tutorials 2023-05-27 20:11:34
海外TECH DEV Community Reset/Forgot password on a rest api with jsonwebtoken (jwt) in express https://dev.to/renzhamin/resetforgot-password-on-a-rest-api-with-jsonwebtoken-jwt-in-express-6i9 Reset Forgot password on a rest api with jsonwebtoken jwt in express Overview Add password reset functionality on top of a rest api that has authentication and authorization implemented If you want to know the basics of how jsonwebtoken is used for authorization you can read here Prisma ORM is used with SQLite So you don t have to setup any database in your system This approach is stateless and requires the least amount of db calls therefore prioritizing performance The code is available on github Flow Table of ContentsToken GenerationWhy keep the validity duration small Why not just use regular accessToken Sending EmailHow to enable app password in google accountSending the reset linkResetting passwordPassword Reset FormUpdating password Token Generationutils genToken ts helper function to generate tokenexport const genToken user any secret string expiresIn string tokenId string gt const id username email user const jwtid tokenId randomUUID const token jwt sign jwtid id username email secret algorithm HS expiresIn return token Generate a token with a minute expiration time lesser the better Use an environment variable as secret this should be large and randomexport const genPassResetToken user gt return genToken user process env PASS RESET TOKEN SECRET m Why keep the validity duration small As we are using stateless jwt we can not invalidate the token To prevent a user from using the same link again and again we must set the expiration time to a lower value Why not just use regular accessToken A regular access token provides access to protected resources which we don t want at all The user only provides a email address they may or may not be a legitimate user Thats why we can t just hand over an accessToken on a password reset request Sending EmailThere are multiple ways to send email from a server Here is a sample code to setup a gmail account to send an email using nodemailer utils sendEmail ts export const sendEmail async receiverEmail subject body gt const transporter nodemailer createTransport service gmail auth your gmail address user process env serviceEmail app password for the gmail pass process env serviceEmailPassword const mailOptions from process env serviceEmail to receiverEmail subject subject html body transporter sendMail mailOptions error info gt if error console log Failed to send email to receiverEmail else console log Email sent info response How to enable app password in google accountGo to google account pageNavigate to security and enable step verificationSearch App Passwords in the search bar and click on the matched resultChose app as Mail and device as Other and put anything thereClick on GENERATE button and save the password as serviceEmailPassword in env file NOTE you only get one chance to save the password Sending the reset linkcontrollers passReset ts Route GET api pass reset expecting email in request bodyexport const getPassResetLink async req res gt try if req body email return res status json msg No email provided const user await findUserByEmail req body email if user user email return res json msg Email not found const token genPassResetToken user const requrl req protocol req get host req originalUrl the url from which the request came from in local environment it is http localhost api pass reset if the frontend is in different domain declare PASS RESET URL in env file const url process env PASS RESET URL requrl const resetLink lt a target blank href url user id token gt Password Reset Link lt a gt sendEmail req body email Reset Password resetLink res json msg Password Reset Link sent to email catch error res status json msg Failed to send email Resetting password Password Reset Form The frontend should have a route PASS RESET URL userId token that takes an email in the body which sends a POST request to api pass reset userId token on submit Here I have created the most basic html form to keep this article backend focusedutils passReset ts Route GET api pass reset userId tokenexport const getPassResetPage req res gt const userId token req params res send lt form action api pass reset userId token method POST gt lt input type password name password value placeholder Enter your new password gt lt input type submit value Reset Password gt lt form gt Updating passwordRoute router post api pass reset userId token verifyPasswordResetToken passReset verifyPasswordResetToken middleware verifies the token with the secret PASS RESET TOKEN SECRETutils passReset ts export const passReset async req res gt try const password req body if password return res send Password not provided updatePassword req params userId password res json msg Password Reset Successfull catch error res status send Failed to reset password IMPORTANT Hash the password before saving it in the database Ensure that you use the same hash function for password hashing in every cases such as user creation change password reset passworddb users ts export const updatePassword async userId string newPassword string gt newPassword await hashString newPassword return db user update where id userId data password newPassword Find me onGithubLinkedInTwitter 2023-05-27 20:02:00
ニュース BBC News - Home Bayern Munich beat Cologne 2-1 and Borussia Dortmund draw means Bayern are champions https://www.bbc.co.uk/sport/football/65714772?at_medium=RSS&at_campaign=KARANGA Bayern Munich beat Cologne and Borussia Dortmund draw means Bayern are championsBayern Munich win an th successive Bundesliga title as they overhaul Borussia Dortmund on the final day of the season 2023-05-27 20:46:19
ビジネス ダイヤモンド・オンライン - 新着記事 複数の物言う株主があなたの会社に群がる悪夢…狙われないための「防衛術」を伝授【後編】 - 激安株を狙え https://diamond.jp/articles/-/323134 上場企業 2023-05-28 05:25:00
ビジネス ダイヤモンド・オンライン - 新着記事 【無料公開】損害保険ジャパン社長に聞く、契約者の事故・被災対応部門1万人の「品質向上」を宣言した理由 - Diamond Premiumセレクション https://diamond.jp/articles/-/323584 diamond 2023-05-28 05:20:00
ビジネス ダイヤモンド・オンライン - 新着記事 小学校お受験「最強の時間割」、フルタイム共働き母と子が1年で難関校合格を実現 - 幼児教育&お受験のリアル https://diamond.jp/articles/-/322973 小学校受験 2023-05-28 05:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 日本人の「英語力格差」はChatGPT・AI翻訳で拡大する!苦手な人が大化けの可能性も - ビジネスを強くする教養 https://diamond.jp/articles/-/323398 chatgpt 2023-05-28 05:10:00
ビジネス ダイヤモンド・オンライン - 新着記事 佐藤優が暴く、プーチンの盟友・ワグネル代表が「ロシア猛烈批判」を始めた理由【見逃し配信】 - 見逃し配信 https://diamond.jp/articles/-/323564 関連 2023-05-28 05:05:00
ビジネス 東洋経済オンライン ダイソン、「家族経営だからできる」2代目の挑戦 創業者の息子が語った「ヘッドホン」開発の内幕 | IT・電機・半導体・部品 | 東洋経済オンライン https://toyokeizai.net/articles/-/674910?utm_source=rss&utm_medium=http&utm_campaign=link_back 東洋経済オンライン 2023-05-28 05:30:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)