投稿時間:2021-04-24 18:26:58 RSSフィード2021-04-24 18:00 分まとめ(31件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] コロナ禍でもヒットした映画「劇場版鬼滅の刃 無限列車編」『シン・エヴァンゲリオン劇場版』 ヒットの要因は? https://www.itmedia.co.jp/business/articles/2104/24/news017.html gempartners 2021-04-24 17:20:00
python Pythonタグが付けられた新着投稿 - Qiita music2vecを用いた音楽ジャンル分類モデル https://qiita.com/KMASAHIRO/items/cae4dfb0657eec4a2dca しかし、データセットの違いにより・分類ジャンル数が記事ではつなのに対して今回は個で分類をしている・記事のモデルでは入力が小さいこともありおよそ個のデータを使用しているのに対し、今回は個のデータを使用しているという違いがあるので、今回の結果は悪くないと考えられます。 2021-04-24 17:56:04
python Pythonタグが付けられた新着投稿 - Qiita (3)「簡単な技術紹介」と「作ったアプリ」の詳細について https://qiita.com/suzuki-masaomi/items/d865532c3d18cccaf802 精度もまで出たので、そこそこ良いのではないかと感じました。 2021-04-24 17:33:31
python Pythonタグが付けられた新着投稿 - Qiita (2)30代後半で”WEB App”を作る(作成の全体的な流れ) https://qiita.com/suzuki-masaomi/items/afd4cc8df8416469043a ー大まかには、どんな「画像識別のWEBアプリ」を作るか決める実際に作れそうなテーマに絞る画像を集める画像の下処理をする「ディープラーニングのモデル」アプリの中身を作るWEBアプリの「外側」を作るHTMLCSSデプロイするWEB上に公開する完成という流れです。 2021-04-24 17:32:38
python Pythonタグが付けられた新着投稿 - Qiita (1)30代後半で「機械学習」を学んだ記録 https://qiita.com/suzuki-masaomi/items/b7a0e74c28c968a4632a 自分は非正規雇用の年月が極めて長いので、職業が安定しない分は「確かな知識」で補っていかないといけないのですが、どの分野の仕事に向かうとしても「ITの知識は、必ず知っておくべき汎用的な知識」という観点から学ぶことにしました。 2021-04-24 17:31:35
python Pythonタグが付けられた新着投稿 - Qiita 一緒にPythonを始めよう https://qiita.com/kyuko_dance/items/4cc6933d0a85829e0d0f だったらどうするかということで、当てずっぽうでからxの間にある適当な数aを選び、aとxを比較してみます。 2021-04-24 17:29:34
js JavaScriptタグが付けられた新着投稿 - Qiita PrismaでMySQLを利用して開始するときにエラーが発生する場合 https://qiita.com/makoll/items/4df94068f570aebf39af 2021-04-24 17:35:13
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) プレイヤーが視界に入ったら追従したい。 https://teratail.com/questions/334959?rss=all この中に入ったら敵キャラの向きをプレイヤーの向きに変え、追従を行いたいです。 2021-04-24 17:56:04
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) C言語において、文字列をscanf_sで使用したいです。 https://teratail.com/questions/334958?rss=all C言語において、文字列をscanfsで使用したいです。 2021-04-24 17:39:44
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Excel VBAのエラー対応「実行時エラー:6 オーバーフローしました。」 https://teratail.com/questions/334957?rss=all ExcelVBAのエラー対応「実行時エラーオーバーフローしました。 2021-04-24 17:35:03
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) bundle update rails した際に Failed to build gem native extension.エラー出る https://teratail.com/questions/334956?rss=all bundleupdaterailsした際にFailedtobuildgemnativeextensionエラー出るmimemagicのGPL混入問題の対策としてrailsnbspのバージョンをあげようと試みましたがgemfile書き換えてbundlenbspupdatenbsprailsした際にエラーが出ます。 2021-04-24 17:29:43
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Vue3でのコンポーネントのグローバル登録方法について https://teratail.com/questions/334955?rss=all Vueでのコンポーネントのグローバル登録方法についてVueでのコンポーネントのグローバル登録方法を教えてくださいvue初心者です。 2021-04-24 17:21:29
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Javascript: 配列の要素の並べ方を全パターン網羅したい https://teratail.com/questions/334954?rss=all constarr 2021-04-24 17:10:28
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Python PandasのDataFrameで、3つのカラムに別々に入った年・月・日を結合し、datetimeにしたいです。 https://teratail.com/questions/334953?rss=all PythonPandasのDataFrameで、つのカラムに別々に入った年・月・日を結合し、datetimeにしたいです。 2021-04-24 17:05:57
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) [python × Youtube API]動画のコメントを取得できないcommentThreads() https://teratail.com/questions/334952?rss=all python×YoutubeAPI動画のコメントを取得できないcommentThreads前提・実現したいことcommentThreadsメソッドを使ってチャンネルIDに紐付けられたコメントを全て取得したいと思っています。 2021-04-24 17:01:44
Ruby Rubyタグが付けられた新着投稿 - Qiita Rubyを使って画像をRPGツクールMV用のマップに変換する https://qiita.com/haverisxa/items/bb3163f5a9526cd57d23 2021-04-24 17:43:30
Azure Azureタグが付けられた新着投稿 - Qiita Autonomous DatabaseとAzure Blob Storageを連携したときの自分用メモ https://qiita.com/TakuyaAma/items/3129ac8039e1560d742f AutonomousDatabaseとAzureBlobStorageを連携したときの自分用メモこの記事で記載することAutonomousDatabaseADBからAzureBlobStorageBlob上のデータを、取り扱うための方法について自分用メモを記載します。 2021-04-24 17:28:46
海外TECH DEV Community build a social media website with Next JS and Firebase https://dev.to/namanvyas/build-a-social-media-website-with-next-js-and-firebase-3i3k build a social media website with Next JS and FirebaseHello Everyone As the title say I created a social media website with Next JS framework and Firebase Its a basic and simple social media just for learning new stuff about Next JS and Firebase Website Link Github Link This website is still in development What I am Going To AddAll post by user on profileLike and comment systemSuggestions systemFollow System And many more stuffTell me what you think about it Also feel free to contribute 2021-04-24 08:14:37
海外TECH DEV Community Implement login user API that returns PASETO or JWT access token in Go https://dev.to/techschoolguru/implement-login-user-api-that-returns-paseto-or-jwt-access-token-in-go-5b1p Implement login user API that returns PASETO or JWT access token in GoHello everyone Welcome back to the backend master class In the previous lecture we ve implemented the token maker interface using JWT and PASETO It provides methods to create and verify tokens So today we re gonna learn how to use it to implement the login API where the username and password are provided by the client and the server will return an access token if those credentials are correct Here s Link to the full series playlist on YoutubeAnd its Github repositoryOK let s start Add token Maker to the ServerThe first step is to add the token maker to our API server So let s open api server go file In the Server struct I m gonna add a tokenMaker field of type token Maker interface type Server struct store db Store tokenMaker token Maker router gin Engine Then let s initialize this field inside the NewServer function First we have to create a new token maker object We can choose to use either JWT or PASETO they both implement the same token Maker interface I think PASETO is better so let s call token NewPasetoMaker It requires a symmetric key string so we will need to load this from environment variable For now let s just put an empty string here as a placeholder If the returned error is not nil we return a nil server and an error saying cannot create token maker The w is used to wrap the original error func NewServer store db Store Server error tokenMaker err token NewPasetoMaker if err nil return nil fmt Errorf cannot create token maker w err server amp Server store store tokenMaker tokenMaker return server nil OK so now we have to change the return type of the NewServer function to include an error as well Then in the statement to create a Server object we add the tokenMaker object that we ve just created Alright now let s come back to the symmetric key parameter I m gonna add a new environment variable to the app env file Let s call it TOKEN SYMMETRIC KEY And as we re using PASETO version which uses ChachaPoly algorithm the size of this symmetric key should be exactly bytes TOKEN SYMMETRIC KEY ACCESS TOKEN DURATION mWe should also add more variable to store the valid duration of the access token It s a best practice to set this to a very short duration let s say just minutes for example OK now we have to update our config struct to include the new variables that we ve just added First the TokenSymmetricKey of type string We have to specify the mapstructure tag for it because viper uses mapstructure package to parse the config data Please refer to the lecture of the course if you don t know how to use viper type Config struct TokenSymmetricKey string mapstructure TOKEN SYMMETRIC KEY AccessTokenDuration time Duration mapstructure ACCESS TOKEN DURATION The next field is AccessTokenDuration of type time Duration And its mapstructure tag should be this environment variable s name ACCESS TOKEN DURATION As you can see when the type of a config field is time Duration we can specify the value in a human readable format like this m OK so now we ve loaded the secret key and token duration into the config let s go back to the server and use them We have to add a config parameter to the NewServer function Then in the token NewPasetoMaker call we pass in config TokenSymmetricKey We should also add a config field to the Server struct and store it here when initialize the Server object We will use the TokenDuration in this config object later when creating the tokens type Server struct config util Config store db Store tokenMaker token Maker router gin Engine func NewServer config util Config store db Store Server error tokenMaker err token NewPasetoMaker config TokenSymmetricKey if err nil return nil fmt Errorf cannot create token maker w err server amp Server config config store store tokenMaker tokenMaker if v ok binding Validator Engine validator Validate ok v RegisterValidation currency validCurrency server setupRouter return server nil At the end of this function we should return a nil error And that will be it However as we added a new config parameter to the NewServer function some unit tests that we wrote before are broken So let s fix them Fix broken unit testsIn the api main test go file I m gonna define a function newTestServer that will create a new server for test It takes a testing T object and a db Store interface as input And it will return a Server object as output In this function let s create a new config object with TokenSymmetricKey is util RandomString of characters and AccessTokenDuration is minute func newTestServer t testing T store db Store Server config util Config TokenSymmetricKey util RandomString AccessTokenDuration time Minute server err NewServer config store require NoError t err return server Then we create a new server with that config object and the input store interface Require no errors and finally return the created server Now get back to the api transfer test go file Here instead of NewServer we will call newTestServer and pass in the testing T object and the mock store func TestTransferAPI t testing T for i range testCases tc testCases i t Run tc name func t testing T server newTestServer t store recorder httptest NewRecorder We do the same for the server inside api user test go file and api account test go file as well There are several calls of NewServer in these files so we have to change all of them to newTestServer Alright now everything is updated Let s run the whole api package tests All passed Excellent So the tests are now working well with the new Server struct But there s one more place we need to update that s the main entry point of our server main gofunc main config err util LoadConfig if err nil log Fatal cannot load config err conn err sql Open config DBDriver config DBSource if err nil log Fatal cannot connect to db err store db NewStore conn server err api NewServer config store if err nil log Fatal cannot create server err err server Start config ServerAddress if err nil log Fatal cannot start server err Here in this main function we have to add config to the api NewServer call And this call will return a server and an error If error is not nil we just write a fatal log saying cannot create server Just like that and we re done Now it s time to build the login user API Implement login user handlerLet s open the api user go file The login API s request payload must contain the username and password which is very similar to the createUserRequest type createUserRequest struct Username string json username binding required alphanum Password string json password binding required min FullName string json full name binding required Email string json email binding required email So I m gonna copy this struct and paste it to the end of this file Then let s change the struct name to loginUserRequest and remove the FullName and Email fields just keep the Username and Password fields type loginUserRequest struct Username string json username binding required alphanum Password string json password binding required min Next let s define the loginUserResponse struct The most important field that should be returned to the client is AccessToken string This is the token that we will create using the token maker interface type loginUserResponse struct AccessToken string json access token Beside the access token we might also want to return some information of the logged in user just like the one we returned in the create user API type createUserResponse struct Username string json username FullName string json full name Email string json email PasswordChangedAt time Time json password changed at CreatedAt time Time json created at So to make this struct reusable I m gonna change its name to just userResponse It will be the type of the User field in this loginUserResponse struct type userResponse struct Username string json username FullName string json full name Email string json email PasswordChangedAt time Time json password changed at CreatedAt time Time json created at type loginUserResponse struct AccessToken string json access token User userResponse json user Then let s copy the userResponse object from the createUser handler and define a newUserResponse function at the top func newUserResponse user db User userResponse return userResponse Username user Username FullName user FullName Email user Email PasswordChangedAt user PasswordChangedAt CreatedAt user CreatedAt The role of this function is to convert the input db User object into userResponse The reason we do that is because there s a sensitive data inside the db User struct which is the hashed password that we don t want to expose to the client OK so now in the createUser handler we can just call the newUserResponse function to create the response object func server Server createUser ctx gin Context user err server store CreateUser ctx arg rsp newUserResponse user ctx JSON http StatusOK rsp The newUserResponse function will be useful for our new loginUser handler as well Alright now let s add a new method to the server struct loginUser Similar as in other API handlers this function will take a gin Context object as input Inside we declare a request object of type loginUserRequest and we call the ctx ShouldBindJSON function with a pointer to that request object This will bind all the input parameters of the API into the request object func server Server loginUser ctx gin Context var req loginUserRequest if err ctx ShouldBindJSON amp req err nil ctx JSON http StatusBadRequest errorResponse err return If error is not nil we send a response with status Bad Request to the client together with the errorResponse body to explain why it failed If there s no error we will find the user from the database by calling server store GetUser with the context ctx and req Username func server Server loginUser ctx gin Context user err server store GetUser ctx req Username if err nil if err sql ErrNoRows ctx JSON http StatusNotFound errorResponse err return ctx JSON http StatusInternalServerError errorResponse err return If the error returned by this call is not nil then there are possible cases The first case is when the username doesn t exist which means error equals to sql ErrNoRows In this case we send a response with status Not Found to the client and return immediately The second case is an unexpected error occurs when talking to the database In this case we send a Internal Server Error status to the client and also return right away If everything goes well and no errors occur we will have to check if the password provided by the client is correct or not So we call util CheckPassword with the input req Password and user HashedPassword func server Server loginUser ctx gin Context err util CheckPassword req Password user HashedPassword if err nil ctx JSON http StatusUnauthorized errorResponse err return If this function returns a not nil error then it means the provided password is incorrect We will send a response with status Unauthorized to the client and return Only when the password is correct then we will create a new access token for this user Let s call server tokenMaker CreateToken pass in user Username and server config AccessTokenDuration as input arguments func server Server loginUser ctx gin Context accessToken err server tokenMaker CreateToken user Username server config AccessTokenDuration if err nil ctx JSON http StatusInternalServerError errorResponse err return rsp loginUserResponse AccessToken accessToken User newUserResponse user ctx JSON http StatusOK rsp If an unexpected error occurs we just return Internal Server Error status code Otherwise we will build the loginUserResponse object where AccessToken is the created access token and User is newUserResponse user We then send this response to the client with a OK status code And that s basically it The loginUser handler function is completed func server Server loginUser ctx gin Context var req loginUserRequest if err ctx ShouldBindJSON amp req err nil ctx JSON http StatusBadRequest errorResponse err return user err server store GetUser ctx req Username if err nil if err sql ErrNoRows ctx JSON http StatusNotFound errorResponse err return ctx JSON http StatusInternalServerError errorResponse err return err util CheckPassword req Password user HashedPassword if err nil ctx JSON http StatusUnauthorized errorResponse err return accessToken err server tokenMaker CreateToken user Username server config AccessTokenDuration if err nil ctx JSON http StatusInternalServerError errorResponse err return rsp loginUserResponse AccessToken accessToken User newUserResponse user ctx JSON http StatusOK rsp Add login API route to the serverThe next step is to add a new API endpoint to the server that will route the login request to the loginUser handler I m gonna put it next to the create user route So router POST the path should be users login and the handler function is server loginUser func NewServer config util Config store db Store Server error router gin Default router POST users server createUser router POST users login server loginUser And we re done However this NewServer function is getting quite long now which makes it harder to read So I m gonna split the routing part into a separate method of the server struct Let s call it setupRouter Then paste in all the routing codes func server Server setupRouter router gin Default router POST users server createUser router POST users login server loginUser router POST accounts server createAccount router GET accounts id server getAccount router GET accounts server listAccounts router POST transfers server createTransfer server router router We should move the gin router variable here as well And at the end we should save this router to the server router field Then all we have to do in the NewServer function is to call server setupRouter func NewServer config util Config store db Store Server error tokenMaker err token NewPasetoMaker config TokenSymmetricKey if err nil return nil fmt Errorf cannot create token maker w err server amp Server config config store store tokenMaker tokenMaker if v ok binding Validator Engine validator Validate ok v RegisterValidation currency validCurrency server setupRouter return server nil And now we ve really completed the login user API s implementation It s pretty easy and straightforward isn t it Run the server and send login user requestLet s run the server and send some requests to see how it goes ❯make servergo run main go GIN debug WARNING Creating an Engine instance with the Logger and Recovery middleware already attached GIN debug WARNING Running in debug mode Switch to release mode in production using env export GIN MODE release using code gin SetMode gin ReleaseMode GIN debug POST users gt github com techschool simplebank api Server createUser fm handlers GIN debug POST users login gt github com techschool simplebank api Server loginUser fm handlers GIN debug POST accounts gt github com techschool simplebank api Server createAccount fm handlers GIN debug GET accounts id gt github com techschool simplebank api Server getAccount fm handlers GIN debug GET accounts gt github com techschool simplebank api Server listAccounts fm handlers GIN debug POST transfers gt github com techschool simplebank api Server createTransfer fm handlers GIN debug Listening and serving HTTP on As you can see here the login user API is up and running Now I m gonna open Postman create a new request and set it method to POST The URL should be http localhost users login then select body raw and JSON format The JSON body will have fields username and password In the database there are users that we already created in previous lectures So I m gonna use the first user with username quang and the password is secret OK let s send this request Voilà It s successful We ve got the PASETO v local access token here And all the information of the logged in user in this object So it worked Let s try login with an invalid password xyz Send the request Now we ve got Bad Request because the password we sent was too short That s because we have a validation rule for the password field to have at least characters type loginUserRequest struct Password string json password binding required min So let s change this value to xyz And send the request again This time we ve got Unauthorized status code and the error is hashed password is not the hash of the given password or in other words the provided password is incorrect Now let s try the case when username doesn t exist I m gonna change the username to quang and send the request again This time we ve got Not Found status code That s exactly what we expected So the login user API is working very well Before we finish I m gonna show you how easy it is to change the token types Change the token typeRight now we re using PASETO but since it implements the same token maker interface with JWT it will be super easy if we want to switch to JWT All we have to do is just change the token NewPasetoMaker call to token NewJWTMaker in the api server go file func NewServer config util Config store db Store Server error tokenMaker err token NewJWTMaker config TokenSymmetricKey if err nil return nil fmt Errorf cannot create token maker w err That s it Let s restart the server then go back to Postman and send the login request one more time As you can see the request is successful And now the access token looks different because it s a JWT token not a PASETO token as before OK now as we ve confirmed that it worked I m gonna revert the token type to PASETO because it s better than JWT in my opinion func NewServer config util Config store db Store Server error tokenMaker err token NewPasetoMaker config TokenSymmetricKey if err nil return nil fmt Errorf cannot create token maker w err And that wraps up this lecture about implementing login user API in Go I hope you find it useful Thanks a lot for reading and see you soon in the next one If you like the article please subscribe to our Youtube channel and follow us on Twitter or Facebook for more tutorials in the future 2021-04-24 08:13:04
海外ニュース Japan Times latest articles Challenges abound as Japan eyes new basic energy policy in June https://www.japantimes.co.jp/news/2021/04/24/business/japan-energy-policy/ renewable 2021-04-24 18:48:22
海外ニュース Japan Times latest articles Australian women leading nation’s athletics revival ahead of Tokyo Games https://www.japantimes.co.jp/sports/2021/04/24/olympics/summer-olympics/olympics-track-and-field/australian-women-leading-athletics/ strong 2021-04-24 19:00:14
海外ニュース Japan Times latest articles How to make tonpeiyaki cabbage and pork omelette https://www.japantimes.co.jp/life/2021/04/24/food/tonpeiyaki-cabbage-pork-omelette/ quick 2021-04-24 18:45:58
海外ニュース Japan Times latest articles Plan to discharge Fukushima plant water into sea sets a dangerous precedent https://www.japantimes.co.jp/opinion/2021/04/24/commentary/japan-commentary/fukushima-radiation-3-11-nuclear-energy-radioactive-water-iaea/ Plan to discharge Fukushima plant water into sea sets a dangerous precedentAllowing the release to proceed unilaterally without genuine international consultation would set a dangerous precedent and further damage the international rules based agreement system 2021-04-24 19:00:25
海外ニュース Japan Times latest articles Japan-U.S. alliance remains strong, but challenges lie ahead https://www.japantimes.co.jp/opinion/2021/04/24/editorials/japan-u-s-relations-joe-biden-yoshihide-suga/ japan 2021-04-24 19:00:01
ニュース BBC News - Home Dominic Cummings: No 10 defends PM after former aide's blog post https://www.bbc.co.uk/news/uk-politics-56870370 conduct 2021-04-24 08:05:27
ニュース BBC News - Home India Covid surge: Hospitals send SOS as record deaths registered https://www.bbc.co.uk/news/world-asia-56870410 medical 2021-04-24 08:41:07
ニュース BBC News - Home Three-lorry M5 crash in Gloucestershire leaves driver dead https://www.bbc.co.uk/news/uk-england-gloucestershire-56871021 stroud 2021-04-24 08:55:53
ニュース BBC News - Home Boy stabbed to death in Newham, east London https://www.bbc.co.uk/news/uk-england-london-56853980 londonthe 2021-04-24 08:15:30
ニュース BBC News - Home Razzies: Singer Sia named 'worst director' for controversial film Music https://www.bbc.co.uk/news/entertainment-arts-56856540 controversial 2021-04-24 08:25:24
LifeHuck ライフハッカー[日本版] 【Amazon タイムセール祭り】キャンプにおすすめ!ポータブル電源が36%オフ、電池式ランタンが40%オフとお買い得 https://www.lifehacker.jp/2021/04/amazon-timesale-fes-2021-0424-2.html amazon 2021-04-24 17:45:00
ビジネス 東洋経済オンライン 無神経な人にちょっとだけ言い返す技【動画】 徹底的に叩きのめすのではなく「巧みにかわす」 | リーダーシップ・教養・資格・スキル | 東洋経済オンライン https://toyokeizai.net/articles/-/424861?utm_source=rss&utm_medium=http&utm_campaign=link_back 完膚なきまでに 2021-04-24 17:10:00

コメント

このブログの人気の投稿

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

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

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)